IntelliJ Java IDE
The moose likes I/O and Streams and the fly likes Load file inside JAR?? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Reply Bookmark "Load file inside JAR??" Watch "Load file inside JAR??" New topic
Author

Load file inside JAR??

Gary Bryan
Greenhorn

Joined: Jun 30, 2003
Posts: 4
If I have a java program which loads an external file, eg. an image or a text file, the file loads fine if the program's just as a .class file in the same directory as the file, but if I put the class and the file into a JAR, the file won't work, I get file not found exceptions. I have searched around for how to make this work, but with no success. Does anyone know how to get this to work? Thanks.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 23395

If you use a filename, then the filename has to refer to a real file. But if you use a "resource name," that resource might be a file or it might be a component of a JAR (or theoretically something else altogether.)
The magic method(s) in this case are the family of loadResource() methods. For example, Class.getResource().
If youve got a class foo/bar/Test.class inside a JAR file, and also a foo/bar/Image.jpg, then inside the Test class you can refer to Image.jpg using
URL theURL = getClass().getResource("Image.jpg");
and then pass the URL to ImageIcon's constructor for example.


[Jess in Action][AskingGoodQuestions]
 
 
subject: Load file inside JAR??
 
Threads others viewed
Using Tomcat's commons-digester.jar in Servlet
Detect if a .properties file is in a jar
ResourceBundle & jar file
Reading a zip file
Imbedded jar file
Two Laptop Bag