Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Load file inside JAR??  RSS feed

 
Gary Bryan
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!