简体   繁体   中英

Access to resource missing with an exported jar file

If I run the following code within eclipse my program compiles with no issue. If I try to export the program as a runnable jar file my resource cannot be found.

public class Test {

   public static void main(String[] args) {

      File file = new File(Tester.class.getClassLoader().getResource("res/myFile.txt").getFile());

      if(!file.exists()) { System.out.println("File not found."); }
   }

}

Folder structure (by running jar tf test.jar ):

com/

com/test/

com/test/Tester.class

res/

res/myFile.txt

There is no such file in case of jar.

Use instead Tester.class.getResourceAsStream("/myFile.txt") and work with the stream

UPDATE: See more here or here

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