How can I save a file to the class path

Use ClassLoader#getResource() or getResourceAsStream() to obtain them as URL or InputStream from the classpath.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/file.ext");
// ...

Or if it is in the same package as the current class, you can also obtain it as follows:

InputStream input = getClass().getResourceAsStream("file.ext");
// ...

Saving is a story apart. This won't work if the file is located in a JAR file. If you can ensure that the file is expanded and is writable, then convert the URL from getResource() to File.

URL url = classLoader.getResource("com/example/file.ext");
File file = new File(url.toURI().getPath());
// ...

You can then construct a FileOutputStream with it.

Related questions:

  • getResourceAsStream() versus FileInputStream

You can try the following provided your class is loaded from a filesystem.

String basePathOfClass = getClass()
   .getProtectionDomain().getCodeSource().getLocation().getFile();

To get a file in that path you can use

File file = new File(basePathOfClass, "filename.ext");

new File(".").getAbsolutePath() + "relative/path/to/your/files";