NGSoftware
NGSoftware

Reputation: 27

Java won't export my resources properly

So I have 2 class folders one is res the other is lib. My res folder has two other sub folders one with images the other with sounds. My lib folder has 4 other jar files and a native folder. It all works within eclipse but when I try to export it as a runnable jar it does not work. I won't won't recognize anything.

I am to call my images I am using ImageIO.read(new File(imagePath)); For the sound I am using the external libraries I mentioned earlier to load and play them.

Upvotes: 1

Views: 203

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500765

I am to call my images I am using ImageIO.read(new File(imagePath))

Contrary to your title, this is not an Eclipse problem - it's simply a bug in your code, because your code assumes that the image is stored as a file in the file system, when it's not.

You don't have a file for the image, so you shouldn't use new File. You should instead use Class.getResource or ClassLoader.getResource - or the getResourceAsStream equivalents. That way, it will load the resource from whatever context the class itself is loaded, which is appropriate for jar files. So for example, you might have:

Image image = ImageIO.read(MyClass.getResource("foo.png"));

... where foo.png is effectively in the same package structure as the class. Alternatively:

Image image = ImageIO.read(MyClass.getResource("/images/foo/bar.png"));

where images is a folder within the root directory of one of your jar files loaded by the same ClassLoader. (We don't have enough information to give you complete code here, but that should be enough to get you going.)

Upvotes: 1

Related Questions