Referencing an image inside a jar file when running junit - java

I have been playing with the idea of using ImageMagic (im4java) to do a comparison of known good page renders against stored good pages.
I have got this working on a test site, but all my images (good, bad and differrent) are stored in my c:\temp folder. I have been toying with the idea of having the "expected" images kept inside the project folder structure, so when the project is checked out, the expected images are there.
(not saying this is a great solution, this is just something I have been playing with.)
So my test is stored in
/src/test/java/my.screen.test/compareTest.java
and I have my "expected" image in
/masterImages/test.png
I have tried various ways to reference this:
I included masterImages in the build path and then tried to use
InputStream input = getClass().getResourceAsStream("/masterImages/googleHomePage1.png");
(I then thought I could simply use input.toString() to pass into im4java - but the InputStream gave me nullpointer exception)
I also tried removing the masterImages from the buildpath and trying it that way.
I have also tried
String path = getClass().getClassLoader().getResource("masterImages/googleHomePage1.png").toString();
Again, null pointer. I know there is something stupid I am not seeing here, like I said this started as me playing but it's now annoying me why I can't get it to work.
Any insights into what I am missing greatly appreciated.

From - In java, how do you retrieve images from a jar file?
It is indeed simple: you use the various getResource() methods in java.lang.Class and java.lang.ClassLoader. For example, in your app, you could just write
treeURL = getClass().getResource("/images/tree.png");
This would find the file in an images directory at the root of the jar file. The nice thing about the getResource() methods is that they work whether the files are in a jar or not -- if the images directory is a real directory on disk, this will still work (as long as the parent of images is part of your class path.)

Thanks to all. I think I have this sorted. Turns out I had to add the folder containing the image to the classpath - I wrongly assumed that as I had masterImages/otherFolderName that any file inside otherFolderName would be included if I included masterImages. Turns out this is not the case (at least for me.)

Related

cannot create inputstream for ico file

I tried to create an InputStream pointing at an .ico file, which is in a directory in the src directory. I also create an InputStream for a different jar file in my src.
InputStream inIco = Installer.class.getResourceAsStream("/res/" + iconName + ".ico");
InputStream inApp = Installer.class.getResourceAsStream("/res/" + applicationName + ".jar");
that is how I tried to load it. The inputstream for the jar file works, but the other one is null.
Edit: Sorry for the confusion guys. I didn't build the jar, I just ran it from my editor, which obviously gives me different results, now it is working. Thanks for your answers.
getResourceAsStream (gRAS) loads from the same place java loads class files. That's great - it means you can ship your app as a jar and put these resources inside. If it's not working for you, you've misconfigured your build. Specifically, java is first going to determine the classpath root of your Installer.class file and looks there. If you're not sure what that is, run this code:
System.out.println(Installer.class.getResource("Installer.class"));
which will print something like jar:file:/Users/carlos/projects/FooBar/dist/foobar.jar!com/foo/Installer.class
and this tells you that gRAS is going to look in that foobar.jar file.
From there, the resource is loaded relatively to the root (because of that leading slash): Within that jar, it will look for /res/app.ico. Without it, it loads relative to the same dir/package of Installer class (in this example above, gRAS("hello.txt") is the same as gRAS("/com/foo/hello.txt").
To make this work out, your build system is responsible. For maven and gradle, have src/main/java/com/foo/Installer.java along with src/main/resources/res/icon.ico and all should be well. If this is not working out, explain how you've set up your environment because something is misconfigured if this isn't working. If you're using another build tool (such as perhaps ant, sbt, or relying on your IDE to take care of it), name the tool and perhaps we can help address the misconfiguration.

tuProlog - using multiple files with consult - can't get engine to load additional files with consult(otherFile.pl)

Edit: Clarity - the main .pl file loads, it's all the subfiles that it has been told to load which don't load. (all the consult('subfile.pl').)
I have a Java project that uses tuProlog. It calls a theory as:
Theory theory = new Theory(":-consult('main.pl').");
engine.setTheory(theory);
This is as per the manual.
file.pl exists in the same folder as other prolog files.
Inside of main.pl, I have further
consult('otherfile.pl').
statements to load additional files (several).
The folder structure is:
src/main.pl
src/Prolog_Files/otherfile.pl (multiple)
src/main/java/JavaStuff
I can't get the engine to load the theories that I've told it to consult inside of the main file.pl
I have tried: giving it absolute path instead of just filename.
moving files around.
I'm wondering if there is something about usage of tuProlog I'm not understanding?
The theory works when loaded with:
Theory theory = new Theory(new FileInputStream(url_of_file)).
However, this is causing me issues when building the jar, as it can't find the file location.
Am I attempting to load the file correctly? Are my consults inside of the main .pl file correct?
Could someone please post an example of how this should be done if not? The manual doesn't elaborate very much on this topic.
Thanks
The manual is slightly outdated in parts - it says to use consult/1, whereas elsewhere it states that consult/1 is deprecated, whereas include/1 is the replacement.
Secondly, when using 2p.jar, it reads Prolog files from the Project root as its root. When creating a jar, 2p.jar cannot be inside of the project jar. They should be in relative folders, and 2p.jar reads Prolog files with the location of 2p.jar as root. It doesn't seem that it can read inside of project jar.
Hopefully that's clear enough!

Null pointer exception while loading image in JApplet

I am gettting a nullpointer excetion when i run the applet in browser, while its working fine through appletviewer.
titleicon=new ImageIcon(this.getClass().getClassLoader().getResource("image.jpg"));
img=new JLabel(titleicon)
File locations: Both .class file and image file are in same folder.
C:\project\game.class
C:\project\image.jpg
I tried differennt variations below, none is working in browser but all are fine with appletviewer:
titleicon=new ImageIcon(this.getClass().getResource("image.jpg"));
titleicon=new ImageIcon(getClass().getClassLoader().getResource("image.jpg"));
With a file location of
C:\project\game.class
C:\project\image.jpg
Class.getResource will never work, as this searches the classpath for the required resources.
The use of getResource assumes that the resources are embedded and are relative to the class path.
Without more details, it's difficult to make an accurate suggestion, but I would suggest that you get the images jared without your application code, this way, it will be easier to find.
If you're not using an IDE capable of Jaring your classes and resources, then you will need to have a look at Packaging Programs in JAR Files
Remember, Class#getResource is capable of doing a relative lookup. If the images are not stored in the same package as the class which is loading them, then you need to use an absolute path instead...

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.

Java: NullPointerException from class.getResource( ... )

I was writing a small application and when I tried to create an ImageIcon I always got an exception. The exception was caused by this line of code:
prayerLevel.setIcon(new ImageIcon(getClass().getResource("/icons/icon_prayer.png")));
Now within my program, the folder /icons/ does exist. I don't know if it makes the difference but the class file is within a package, where as the icons folder is within the project folder (when you would see the bin and src folder).
I have looked around for a bit and I couldn't find a solution that could help me solve the problem. Perhaps any of you guys could help?
Edit: someone asked for my folder hierarchy:
I know the class file is not in the same folder as the icons are, but I've made applications where I had to load files from a different folder and doing /folder/ always used to work.
Edit 2:
System.out.println(getClass().getResource("/icons/icon_prayer.png") == null);
Prints true.
I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.
Try the following:
getClass().getClassLoader().getResource("/icons/icon_prayer.png")
Or:
ClassLoader.getSystemResource("/icons/icon_prayer.png")
As far as I know getResource() will look into locations of known resources, in other words if the folder /icons/ is not seen as a resource folder it will not as you had expected. There are two ways of going around this as far as I know:
1) Set icons folder as a resource to the application, then you can use getResource() for instance
URL css_url = getClass().getResource("/resource/style.css");
For more info on this option, see http://lj4newbies.blogspot.com/2008/03/using-classgetresource-load-resource.html
2) Get the icon as a regular file without using getResource() method. This is actually adviced in Swing tutorials on Sun/Oracle own documentation .
Generally, applications provide their own set of images used as part
of the application, as is the case
with the images used by many of our
demos. You should use the Class
getResource method to obtain the path
to the image. This allows the
application to verify that the image
is available and to provide sensible
error handling if it is not. When the
image is not part of the application,
getResource should not be used and the
ImageIcon constructor is used
directly. For example:
ImageIcon icon = new
ImageIcon("images/middle.gif",
"a pretty but meaningless splat");
Hope this helps, good luck!
Old thread but since I bumped into a similar problem just now...
I'm using Eclipse and I copied a file to the "resources" folder using system commands (cp). However, eclipse threw a NullPointerException because I didn't refresh the "resources" folder. So the file was there but Eclipse didn't see it.
So in Eclipse: "Package Explorer" -> "resources" -> Mouse right click -> refresh. This fixed it for me.
I added my music, images, etc to a folder added to the build path. Then I just used
URL url="CurrentClass".class.getClassLoader().getResource("media file name not the path");
setIconImage(new ImageIcon(url.getPath()).getImage());
to set the image icon.
The only thing that can throw a NullPointerException in this line of code is the first ., which means that prayerLevel is null.

Categories