Using an image in a JAR file - java

I can't seem to get this right...
I have a Java project in Eclipse called MyProject. In its root is the folders bin, src, and resources. Inside of resources, I have an image named myImage.gif.
In my code, I want to use this image, and I want it to work whether or not this is running from a Jar file. I currently am doing this
ImageIcon j = new ImageIcon(getClass().getResource("/resources/myImage.gif"));
but it is spitting out a null when I run it through Eclipse (not as a Jar).
What is the right way to do this?

If you were to tell Eclipse to treat resources as a source folder then you should be able to say
ImageIcon j = new ImageIcon(getClass().getResource("/myImage.gif"));
When you come to build the JAR you'll have to ensure that the contents of the resources directory go into the top level of the JAR file in order for the same path to work in the JAR case, i.e.
META-INF
MANIFEST.MF
com
example
MyClass.class
myImage.gif
Alternatively, and probably the more common Java idiom, put the image file in the same directory as the .java file (src/com/example in this case) and then use getResource without the leading slash
new ImageIcon(getClass().getResource("myImage.gif"));
Class.getResource resolves a relative path like that against the package of the class in question. Again, you need to have the same structure in the JAR when you come to build that, this time with myImage.gif under com/example.

Place resources into src and Eclipse will copy it into bin.
ImageIcon ii =
new ImageIcon(
ImageIO.read(
getClass().getClassLoader().getResourceAsStream(
"resources/myImage.gif" )));
Without / before the path.

Related

Unable to use images in Intellij IDEA [duplicate]

I have a Java Project in NetBeans 7.0.
I want to add some image to some label dynamically. The image will differ depending on the state of the program.
I put one such image, 'filling.jpg', in the 'resources' folder of my project.
I want to reach this file correctly (not by absolute or relative path, because that will cause problems when I build the jar file).
So I found this method:
ImageIcon fillingIcon = new ImageIcon(getClass().getClassLoader().getResource("filling.jpg"));
labelFontFilling.setIcon(fillingIcon);
It keeps give me java.lang.NullPointerException.
But I am sure that there is that image, because I can assign the image to the label from the NetBeans Properties menu for that label (but I don't want this, I want to add the image by Java code).
What am I doing wrong, and how can I get that image correctly?
This was a pain, using netBeans IDE 7.2.
You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
Add a resource folder to the src folder:
(project)
src
project package folder (contains .java files)
resources (whatever name you want)
images (optional subfolders)
After the clean/build this structure is propogated into the Build folder:
(project)
build
classes
project package folder (contains generated .class files)
resources (your resources)
images (your optional subfolders)
To access the resources:
dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));
and:
if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {
worked for me. Note that in one case there is a leading "/" and in the other there isn't.
So the root of the path to the resources is the "classes" folder within the build folder.
Double click on the executable jar file in the dist folder. The path to the resources still works.
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Project Folder
build
dist
lib
nbproject
resources
src
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image.
In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
For me it worked like I had images in icons folder under src and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

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

Find a resource both in .jar and eclipse with the same String computation

I want to get the path to a resource for ImageIO to read out a BufferedImage from some .png s.
While developing the project I use a relative path to "/bin/stuff/icons/image.png" , but this will definetly not work when I put everything together into a .jar file, so I need a way to get the path to these resources both while testing in eclipse and when later running it within a .jar .
After a lot of trying out both finding the file and getting the input stream to the file I came to the conclusion that this approach works every time:
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(path)
BufferedImage image = ImageIO.read(in)
Where path is
"projectName/resourceFolder/" + nameOfResource.stuff
as found in the src directory of the eclipse project.
E.g.
"myProject/images/icon.png"
When getting only the resource and then getting the path of the resource to link to a file, you will get FileNotFoundExceptions when using a .jar (but not while testing with eclipse, so one should be warned to think that his code works).
And - no - I don't save images in the bin/ - but they are copied to this directory and thus I find them there while testing. Now everything seems to be working.
Don't put anything under the bin directory in Eclipse: if you run a clean on the project it will be erased.
What you can do is to define a new source folder like resources, and put the image there. This way it will be automatically copied to the bin folder.
If you include the resources folder into the Jar, it will be available in both environments by using something like:
ImageIO.read( getClass().getResource("/image.png") )
PS: You can evade using a different resources folder but mixing the sources and images will quickly pollute your source folder.

Accessing images in Java ME

I used following code to access an image from "res" folder with NetBeans
imgWelcome = Image.createImage("/cover.png");
img = new ImageItem(null, imgWelcome, ImageItem.LAYOUT_CENTER, "");
Though the resource is not getting detected and i keep on getting NullPointerException. As weird as it sounds, exactly same technique worked in my previous program.
What am I doing wrong here?
P.S. I've double checked that the file exists in the res folder
There might be many reasons for this, but I have found that most of the time, it is due to how the project is built. Some build scripts include the resources in the res/ folder as top-level files, and some include that folder as a folder in the jar file.
What I have always done to troubleshoot is to rename the jar output to zip and look inside. If the image files are contained in a folder then you should address them as such.
Your code will not find cover.png if it is in the /res folder.
Inspect the contents of your jar using 7-Zip or similar, ensure the image really is in the /res folder, then replace the first line with imgWelcome = Image.createImage("/res/cover.png");.
Oh wow.. this was because .png was not supported by my emulator. And what all I tried :(

Java JAR: Writing to a file

Currently, in my eclipse project, I have a file that I write to. However, I have exported my project to a JAR file and writing to that directory no longer works. I know I need to treat this file as a classpath resource, but how do I do this with a BufferedWriter?
You shouldn't have to treat it as a classpath resource to write to a file. You would only have to do that if the file was in your JAR file, but you don't want to write to a file contained within your JAR file do you?
You should still be able to create and write to a file but it will probably be relative to the working directory - the directory you execute your JAR file from (unless you use an absolute path). In eclipse, configure the working directory from within the run configuration dialog.
You're probably working in Linux. Because, in Linux, when you start your application from a JAR, the working directory is set to your home folder (/home/yourname/). When you start it from Eclipse, the working directory is set to the project folder.
To make sure you really know the files you are using are located in the project folder, or the folder where your JAR is in, you can use this piece of code to know where the JAR is located, then use the File(File parent, String name) constructor to create your files:
// Find out where the JAR is:
String path = YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
path = path.substring(0, path.lastIndexOf('/')+1);
// Create the project-folder-file:
File root = new File(path);
And, from now on, you can create all your File's like this:
File myFile = new File(root, "config.xml");
Of course, root has to be in your scope.
Such resources (when altered) are best stored in a sub-directory of user.home. It is a reproducible path that the user should have write access to. You might use the package name of the main class as a basis for the sub-directory. E.G.
our.com.Main -> ${user.home}/our/com/

Categories