nullByteMe
nullByteMe

Reputation: 6391

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

Upvotes: 0

Views: 917

Answers (1)

StanislavL
StanislavL

Reputation: 57381

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

Upvotes: 1

Related Questions