• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Load file inside JAR??

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You can thank my dental hygienist for my untimely aliveness. So tiny:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic