4

We have a Jar-file. There are 3 folders:

1-st: META-INF

2-nd: resources

3-rd: classes

How can a class from folder classes get image from folder resources?

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
JaeR
  • 63
  • 3
  • What have you tried so far? Have you at least tried a simple google search for "java resources jar"? there seem to be lots of examples out there... – The Scrum Meister Feb 05 '11 at 08:34
  • Related: http://stackoverflow.com/questions/4675617/my-jar-file-wont-load-images – finnw Feb 05 '11 at 18:16

2 Answers2

2

Here's an example:

String path = "resources/something.png";
BufferedImage img = ImageIO.read(getClass().getClassLoader().getResource(path));

To do it in a static context, like in a static initializer block:

String path = "resources/something.png";
BufferedImage img = ImageIO.read(className.class.getClassLoader().getResource(path));
Matt Eskridge
  • 1,019
  • 10
  • 24
  • If you use the path="/resources/something.png" you can omit the getClassLoader() and just call className.class.getResource(path). – Boris Feb 05 '11 at 08:40
  • A lot of THankS!!! And can we write something in file MANIFEST.MF to point at a folder of any resources? – JaeR Feb 05 '11 at 08:53
1

You want to use ClassLoader.getResource or getResourceAsStream, both of which will allow you to read files stored within your JAR. You can access the class loader with YourClass.class.getClassLoader(). See this question for more details: Load a resource contained in a jar

Community
  • 1
  • 1
ide
  • 19,942
  • 5
  • 64
  • 106