Images will not work in a .jar file - java

When a JAR of an application is created, the images in the application no longer appear. An example of our code for loading images is:
ImageIcon placeHolder = new ImageIcon("src\\Cards\\hidden.png");
We have no idea why this is happening. The application runs as expected if we do not compress it to a JAR; as a JAR, the images simply disappear. We also tried using URLs instead of ImageIcons, but that just causes the program not to run at all.
Any ideas?
EDIT: We are putting the image files into our JAR file in the correct paths, so that's not the problem.

Check the API for the constructor you're calling. The string you pass in is a file path - when the resources are packaged in a JAR, there is no file on the filesystem containing the image, so you can't use this constructor any more.
Instead you'd need to load the resources from a stream, using the classloader, and pull them into a byte array:
byte[] buffer = new byte[IMAGE_MAX_SIZE];
InputStream imageStream = getClassLoader().getResourceAsStream("src\Cards\hidden.png");
imageStream.read(buffer, 0, IMAGE_MAX_SIZE);
ImageIcon placeHolder = new ImageIcon(buffer);
Needs more exception and edge-case handling, of course, but that's the gist of it.

You should load resources from the classpath as such:
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("Cards/hidden.png")
This of course assumes that when you create the JAR, you are actually putting the image files into it.
There is also a method for getting the resource as a URL.

Question: Does the folder src exist in the jar?
Tip: You can open .jar with any unpacking program which supports ZIP to see its contents.
Answer: The way you reference the resource is incorrect, you should do something like getClass().getClassLoader().getResource("Cards/hidden.png") instead.

Related

Java Load From Reasource In Jar

I am having some difficulty loading files from resources in eclipse. In the IDE, loading works fine. In a compiled jar everything breaks.
This works for loading an image inside and outside of a jar:
ImageIO.read(this.getClass().getResourceAsStream("E.png"))
This works only in the IDE for a file object (I know it's messy):
File f = new File(Thread.currentThread().getContextClassLoader().getResource("Overworld.mp3").getPath().replace("%20", " "));
I was hoping that there was a constructor for a file object File(InputStream) so I could use the first method of loading an image (which works flawlessly so far) for a file. This, however doesn't exist.
Is there any other method of loading a file into a file object in such a way that it works in the IDE and in a compiled jar?
Thanks in advance.
(Separate but related question: why does File f = new File(this.getClass().getResource("Overworld.mp3").getFile()); give a MEDIA_UNAVAILABLE exception? The file is in the same package as "E.png" with all other source files in my project)
getResourceAsStream() returns a java.io.InputStream that you can use to read the contents of a resource in a jar as a byte array.
Will this work for you?
Why do you require a java.io.File?
Another way to load resource that placed with your class/jar.
URL url = getClass().getClassLoader().getResourceAsStream(filePath);

Getting location of file as string in resource folder

I have completed a program in eclipse and now I would like to export it as a single runnable jar file. The program contains a resource folder with images and text files in it. This is located beneath the source folder.
The res file is not added to the build path however when I run the program in Eclipse it still works.
The thing that is confusing me is that the res file is being saved into the runnable jar file when I export it as I can open the Jar file with WinRar and I see the folder is there with all the objects in it. But when I run the problem it stops at the point that the resource folder is referenced. To add to my confusion when I manually copy and paste the res folder next to where the runnable jar file is saved and run the program it works exactly as it should do.
Now I know this is something to do with how I reference the files in my code. At the moment I have it like this
reader = new LineNumberReader(new FileReader("res/usernames.txt"));
This works exactly how I want and accesses the res folder without any exceptions - in Eclipse and when I move the resource folder next to the Jar file.
I would like it to work normally but without having a folder outside of the Jar file I would like it all encapsulated in one Jar file.
I did a lot of research and what seems to be a common fix - may I add I don't really know how it works but everyone seems to mention it - is to somewhere use:
myClass().getResource()
When I create a new FileReader it needs a String input however when I use myClass().getResource() it returns a resource and not a string. I also don't have a clue how it is meant to reference the resource folder. Should I move the resource folder into the source folder?
Does anyone know how I can reference the resource folder from within the runnable jar file?
Sorry for rambling question I know what I want for my final product but I'm getting confused by the build paths and referencing from within classes and I have searched online for a long time trying to figure it out.
Resources, when you deploy your software, are not deployed as files in a folder. They are packaged as part of the jar of your application. And you access them by retrieving them from inside the jar. The class loader knows how to retrieve stuff from the jar, and therefore you use your class's class loader to get the information.
This means you cannot use things like FileReader on them, or anything else that expects a file. The resources are not files anymore. They are bundles of bytes sitting inside the jar which only the class loader knows how to retrieve.
If the resources are things like images etc., that can be used by java classes that know how to access resource URLs (that is, get the data from the jar when they are given its location in the jar), you can use the ClassLoader.getResource(String) method to get the URL and pass it to the class that handles them.
If you have anything you want to do directly with the data in the resource, which you would usually do by reading it from a file, you can instead use the method ClassLoader.getResourceAsStream(String).
This method returns an InputStream, which you can use like any other InputStream - apply a Reader to it or something like that.
So you can change your code to something like:
InputStream is = myClass().getResourceAsStream("res/usernames.txt");
reader = new LineNumberReader( new InputStreamReader(is) );
Note that I used the getResourceAsStream() method from Class rather than ClassLoader. There is a little difference in the way the two versions look for the resource inside the jar. Please read the relevant documentation for Class and ClassLoader.

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.
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.)

Why is my BufferedImage receiving a null value from ImageIO.read()

BufferedImage = ImageIO.read(getClass().getResourceAsStream("/Images/player.gif"));
First of all, yes I did add the image folder to my classpath.
For this I receive the error java.lang.IllegalArgumentException: input == null!
I don't understand why the above code doesn't work. From everything I read, I don't see why it wouldn't. I've been told I should be using FileInputStream instead of GetResourceAsStream, but, as I just said, I don't see why. I've read documentation on the methods and various guides and this seems like it would work.
Edit: Okay, trying to clear some things up with regards to what I have in the classpath.
This is a project created in Eclipse. Everything is in the project folder DreamGame, including the "Images" folder. DreamGame is, of course, in the classpath. I know this works because I'm reading a text file in /Images with info on the gif earlier on in the code.
So I have: /DreamGame/Images/player.gif
Edit 2: The line that's currently in the original post is all that's being passed; no /DreamGame/Images/player.gif, just /Images/player.gif. This is from a method in the class ImagesLoader which is called when an object from PlayerSprite is created. The main class is DreamGame. I'm running the code right from Eclipse using the Run option with no special parameters
Trying to figure out how to find which class loader is loading the class. Sorry, compared to most people I'm pretty new at this.
Okay, this is what getClassLoader() gets me: sun.misc.Launcher$AppClassLoader#4ba778
getClass().getResource(getClass().getName() + ".class") returns /home/gixugif/Documents/projects/DreamGame/bin/ImagesLoader.class
The image file is being put in bin as well. To double check I deleted the file from bin, cleaned the project, and ran it. Still having the same problem, and the image file is back in bin
Basically, Class.getResourceAsStream doesn't do what you think it does.
It tries to get a resource relative to that class's classloader - so unless you have a classloader with your filesystem root directory as its root, that won't find the file you're after.
It sounds like you should quite possibly really have something like:
BufferedImage = ImageIO.read(getClass().getResourceAsStream("/Images/player.gif"))
(EDIT: The original code shown was different, and had a full file system path.)
and you make sure that the images are copied into an appropriate place for the classloader of the current class to pick up the Images directory. When you package it into a jar file, you'd want the Images directory in there too.
EDIT: This bit may be the problem:
First of all, yes I did add the image folder to my classpath.
The images folder shouldn't be in the classpath - the parent of the Images folder should be, so that then when the classloader looks for an Images directory, it will find it under its root.
If you use resourceAsStream "/" referes to the root of the classpath entry, not to the root of the file system. looking at the path you are using this might be the reason.
If you load something from some home path you probably should use a FileInputStream. getResourceAsStream is for stuff that you deploy with your app.

NullPointerException when accessing image files in a .jar file

I have pretty much tried everything but still have this same problem. I have the following setup: I have a images.jar containing a folder called 'images' in which there are multiple image files. I add images.jar to the java build path of the project in eclipse, and i've been trying to use the following code to access the individual images in the jar:
URL url = this.getClass().getResource("images/a.png");
ImageIcon icon = new ImageIcon (url);
Unfortunately, the URL object is always NULL. I don't think this has anything to do with where I put images.jar file as it is added to the classpath in eclipse. I have also tried using the path '/images/a.png', but still the same problem. Any suggestion would be extremely welcome! Thanks.
Try this:
URL url = this.getClass().getClassLoader().getResource("images/a.png");
ImageIcon icon = new ImageIcon(url);
Without getClassLoader() invocation you are only able to access resources in JAR file where the code is stored.
I couldn't reproduce your problem, but my theory is that you are running the class from a different place than you think you are -- that the image and the class are in different jars, or the class is read directly from the class file.

Categories