How can I save / load a file that is located where my classes are? I don't the physical path to that location before and I want dynamically to find that file.
I want to load an XML file and write and read to it and I am not sure how to address it.
In general, to include all of the JARs in a given directory, you can use the wildcard * (not *. jar ). The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name.
To check our CLASSPATH on Windows we can open a command prompt and type echo %CLASSPATH%. To check it on a Mac you need to open a terminal and type echo $CLASSPATH.
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With