2

Why does new File(path) doesn't work when I run my application from jar? How should I change this? Now I'm receiving FileNotFound Exception when my application tries to load a file.

final File file = new File("src/main/resources/maps/ParcelsCountyRDMFinal5.shp");
5
  • Provide more details, how are giving the path? is it relative? etc. Feb 15, 2012 at 12:19
  • it works fine from eclipse but when i execute java - jar in cmd it raises exception.
    – ilija
    Feb 15, 2012 at 12:23
  • I am creating that file in the main method. I used maven shade plugin. When I unpack my jar, map folder is next to the folder of a package that contains class where I create file. I tried with new File(object.getClass().getResources("maps/ParcelsCountyRDMFinal5.shp").getPath()) but i got null pointer exception.
    – ilija
    Feb 15, 2012 at 13:38
  • can you unzip the jar and see (1) if the file is actually getting included, (2) what is it's location. Ideally, the maps folder will be on the first level, under that you will have your shp file. If so you should be able to get it's URL using obj.getClass().getResource("/maps/fileName")
    – Nishant
    Feb 16, 2012 at 4:38
  • ah, I see error in my answer.
    – Nishant
    Feb 16, 2012 at 4:38

3 Answers 3

3

If jar created properly, say using Maven, the resources files goes next to class files. It looks something like this:

myapp.jar
 |
 +--- com
 |     +---mycompany
 |            +-- FileOpsClass
 |
 +--- maps
        +-- fileToRead

you can either walk up in directory and access fileToRead, like this for above structure:

  final File file = new File("../../maps/ParcelsCountyRDMFinal5.shp");

or as suggested

  final File file = new File(getClass().getResource("/maps/ParcelsCountyRDMFinal5.shp"));
1

If it is already in the classpath you can get it like this:

File file = new File(getClass().getResource("Relative_Path_From_This_Class_To_YourFileName").getPath());
1

When running eclipse the current working directory is set to the project directory. Hence the relative path works. As the file is zipped into the jar too, better use an InputStream instead of a file.

InputStream in = this.getClass().getResourceAsStream("/resources/maps/ParcelsCountyRDMFinal5.shp");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.