I have a folder structured like this:
MyFolder:
- file1.xml
- file2.xml
- project.jar
But if in a class I use:
File f = new File("file1.xml");
I receive an error, because it doesnt find the file. Why?
I have a folder structured like this:
MyFolder:
But if in a class I use:
File f = new File("file1.xml");
I receive an error, because it doesnt find the file. Why?
If you are using Windows the code you posted will work, but not on Linux where the default parent file is your home. But you can do in any OS by using:
public class MyClass {
public void loadFile() {
URL url = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
File jar = new File(url.toURI());
File f = new File(jar.getParent(), "file1.xml");
//your code
}
}
PS: This needs to be inside project.jar because you are getting the location where you jar file is.
You should use a relative path in your code.
Example: File f = new File("./file1.xml");