1

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?

Simone C.
  • 369
  • 4
  • 14
  • The jar is looking within itself for that file and not finding it. You'll have to explicitly declare the directory, or move the XML files inside your jar file. – ManoDestra Jun 01 '16 at 13:41
  • I cant move the xmls inside my jar, because i have to modify them and update them runtime. – Simone C. Jun 01 '16 at 13:43
  • How do you run your application? And what is your working folder at that time? – Nikem Jun 01 '16 at 13:45
  • Declare the path then. Or reference it from a properties file. Try `./file1.xml` and `./file2.xml` for a start. Or place the XML_DIRECTORY in a properties file that you can read and amend. And refer to them from that root. – ManoDestra Jun 01 '16 at 13:46
  • dupe of http://stackoverflow.com/questions/320542 , http://stackoverflow.com/questions/227486 , http://stackoverflow.com/questions/8775303 etc. –  Jun 01 '16 at 13:59
  • Hmmm. I just ran a test with a simple jar I created with a single Java class and it worked fine without any directory reference. – ManoDestra Jun 01 '16 at 14:02
  • Maybe is because im using Ubuntu? Im going to try with OSX now. – Simone C. Jun 01 '16 at 14:03
  • 1
    Thank you ManoDestra, it worked fine with "./file.xml" :)) – Simone C. Jun 01 '16 at 14:09

2 Answers2

0

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.

fredcrs
  • 3,558
  • 7
  • 33
  • 55
0

You should use a relative path in your code.

Example: File f = new File("./file1.xml");

Mickael
  • 4,458
  • 2
  • 28
  • 40