简体   繁体   中英

Why does new File(path) doesn't work when I run my application from jar?

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");

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"));

如果它已经在类路径中,则可以这样获取:

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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM