Java throwing NullPointerException when loading Images using getClass().getResource() - java

I have an Applet I'm trying to embed into a html file after packaging into a jar file.
Images are loaded in the main Applet Class with the following line
return getImage(getClass().getResource("/../content/"+path));
This works when running through eclipse but when I export it to a jar file I get a Null Pointer Exception. I've done some googling and I've tried to use getResourceAsStream with the following code
InputStream is = new BufferedInputStream(
getClass().getResourceAsStream("/../content/"+path));
return ImageIO.read(is);
but this doesn't work through eclipse.
Content is the top level directory of the images and path is the specified path to the required image. The applet is in a folder called game, which is at the same level as content

It was a comment now i answered it here (as OP said it did help): try putting the content into the same package as the class thats accessing the content and change the paths accordingly and see if that helps. If it does, its a problem with your paths.

I had the same issue. But solved it using :-
<ClassName>.class.getClass().getResource(urlString);
Hope this helps...

You could try this instead.
getClass().getClassLoader().getResourceAsStream(name)
Also, your path looks a bit weird. /.. basically means the parent directory of the root, which cannot possibly work.

Related

Getting resources works from NetBeans Execution Context but not working when jar is executed from comand line

I have a code where i create Java Actions and try to associate Icons with them. One snapshot of code is
FileOpenCommand fileOpen = new FileOpenCommand(this);
fileOpen.putValue("ImageOnly", false);
fileOpen.putValue(Action.NAME, "Open");
fileOpen.putValue(Action.SMALL_ICON, new ImageIcon(getClass().getResource("../resources/File-Open-icon24x24.png")));
fileOpen.putValue(Action.SHORT_DESCRIPTION, "Opens the existing file.");
fileOpen.putValue("Group", "File");
fileOpen.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
this.commands.put("FileOpen", fileOpen);
The accent is on the line where I try to set the Action.SMALL_ICON property to the action. This works when executed in NetBeans environment either in debug or release mode. But when I've tried to execute jar file from the command line, it fails with exception.
Any idea? Anything to do with classpath? Resources folder is put as the package inside the main package.
Thanks in Advance!
I'm not entirely sure what exception is being thrown in your case, although assuming it is a NullPointerException, IOException, or IllegalArgumentException deriving from
fileOpen.putValue(Action.SMALL_ICON, new ImageIcon(getClass().getResource("../resources/File-Open-icon24x24.png")));
Your issue should be resolved simply by adding getClassLoader() between the getClass() and getResource(), like so:
fileOpen.putValue(Action.SMALL_ICON, new ImageIcon(getClass().getClassLoader().getResource("../resources/File-Open-icon24x24.png")));
Additionally, you must be exact in your filenames, specifically the extension. In this case, you are accessing File-Open-icon24x24.png, which will work perfectly fine regardless of whether the actual file is extended by png or PNG within Netbeans, but once exported the extension case matters.
Lastly, if neither of those changes resolve your problem, I would check your filepath, as there is most likely a logical error somewhere down the line.
When using embedded resources in Netbeans, you should have a resources folder containing additional folder or whatever data you need, which you seem to have, but this folder should be located inside the Netbeans project's src folder. getClass().getResource() returns the directory at the top of the package line, meaning if your class package is com.example.code, then the compiler will look for files/folder on the same level as com. Opening the Netbeans src folder you should see the initial com folder. Your resource folder should be placed directly next to that folder, as then it will be properly embedded in the jar file export.
In your code your path is ../resources/File-Open-icon24x24.png, which confuses me as to why you begin with ... I cannot see your folder structure so I cannot give a precise answer on this note, but you may be accessing the wrong location, although I feel like you are not as you said your project runs correctly within Netbeans. However, your resource files may not be correctly encoding into the jar file due to placement as mentioned. To test what your jar file actually contains, make a copy of it (for safety reasons) and change the file extension from jar to zip. You can then look through its contents in Windows Explorer, and see its directory structure. Another debugging trick for folder structures is to create a text file at the URL you are trying to access to see where it is placed.

Why does getResourceAsStream() work in the IDE but not the JAR?

I just want to read a file into my program. The file is located one directory above the working directory at "../f.fsh". So the following code runs correctly when I run it in the IDE
String name="../f.fsh";
InputStream is = getClass().getResourceAsStream(name);
InputStreamReader isreader=new InputStreamReader(is);//CRASHES HERE WITH NULL POINTER EXCEPTION
BufferedReader br = new BufferedReader(isreader);
but when I create a JAR file that has f.fsh zipped inside of it and run it, it crashes when creating the InputStreamReader, because the InputStream is null.
I've read a bunch of answers to questions about input streams and JAR files, and what I got out of it is that I should be using relative paths, but I am already doing that. From what I understand getResourceAsStream() can find files relative to the root of the project, that is what I want. Why does it not work in the JAR? What is going wrong, how can I fix it?
Does it have to do with the classpath? I thought that was only for including files external to the jar being run.
I have also tried, but still fail, when putting a slash in:
InputStream is = getClass().getResourceAsStream("\\"+name);
I looked at: How to get a path to a resource in a Java JAR file andfound that contents of a JAR may not necesarily be accesible as a file. So I tried it with copying the file relative to the jar (one directory up from the jar), and that still fails. In any case I'd like to leave my files in the jar and be able to read them there. I don't know what's going wrong.
You can't use .. with Class.getResourceAsStream().
To load a resource f.fsh in the same package as the class, use SomeClass.class.getResourceAsStream("f.fsh")
To load a resource f.fsh in a sub-package foo.bar of the package of the class, use SomeClass.class.getResourceAsStream("foo/bar/f.fsh")
To load a resource f.fsh in any package com.company.foo.bar, use SomeClass.class.getResourceAsStream("/com/company/foo/bar/f.fsh")
This is described in the javadoc of the getResource() method, although it lacks examples.
If .. works in Class.getResourceAsStream() while running from Eclipse, it's a bug in Eclipse. Eclipse and other IDEs implement custom class loaders to fetch resources from the project at runtime. It looks like the class loader implementation in Eclipse isn't performing all the necessary validations on input to getResourceAsStream() method. In this case the bug is in your favor, but you will still need to rethink how you structure your resources for your code to work in all cases.
it's mandatory that the name of the file is CASE SENSITIVE
it's mandatory to refresh (F5) the project explorer if the file is moved or copied outside Exclipse

Add images to jar

I want to set icon to my JFrame. I do the following:
Image icon = Toolkit.getDefaultToolkit().getImage("src/images/icon.jpg");
this.setIconImage(icon);
It works fine when I run this code from netbeans, but when I try to run this code from jar file, images are not shown in my JFrame. I have tried to load images as resources:
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/src/images/icon.jpg")));
but when I run this code it fails with NullPointerException
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:99)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:113)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
How can I do this work?
edit:
Thanks to all,
the problem was solved by specifying image as
Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("images/icon.JPG"))
As for it seems rather weird, and would be better if it was like
this.setIconImage(new ImageIcon(pathToIcon).getImage());
Assuming your JAR file has a top level directory called images, you can use either:
getClass().getResource("/images/icon.jpg") or
getClass().getClassLoader().getResource("images/icon.jpg")
Looking at the source code of URLImageSource, it appears that the reason that getConnection throws an NPE is that it has a null for the url. And that leads me to suspect that
getClass().getResource("/src/images/icon.jpg")
is returning null. It would do that if it could not locate a resource with that pathname.
I bet that the problem is that you've got the path wrong.
To prove / disprove this, you should run jar tvf on the JAR file, and look for the line that matches "icon.jpg". Is the corresponding pathname the same as what you are using? If not, use the pathname from the matching line in the getResource call and it should work. Alternatively, if the file doesn't show up at all, look at the NetBeans build configs that tell it what to put in the JAR file. (I'm not a NetBeans user, so I can't say where you would need to look ...)
If that leads you absolutely nowhere, another possibility is that getClass().getResource(...) is using a classloader that doesn't know about the JAR file containing the image. (This seems pretty improbable to me ...)
getResource() loads a resource from classpath, not an OS path, and the after compilation your classpath will not include the /src folder, but rather just its contents. So you'd better try /images/icon.jpg.
Also you may find this discussion somewhat useful.
This should do it assuming you can import javax.imageio.ImageIO:
Image icon = ImageIO.read(this.getClass().getResource("/src/images/icon.jpg"));
this.setIconImage(icon);
.."/src/images/icon.jpg"..
The '/src' prefix of the address seems suspicious. Many apps. will provide separate 'src' and 'build' directories, but it normally ends up that the 'src' prefix is not used in the resulting Jar. I recommend trying..
.."/images/icon.jpg"..
& also triple checking that the image is in the location of the Jar that the code is expecting to find it.
For this to work, you should access the images from a directory relative to some fixed class.
For example, if the image files are saved in a directory "images" on the same level as the Toolkit.class, then
this.setIconImage(Toolkit.getDefaultToolkit().getImage(Toolkit.class.getResource("images/icon.jpg")));
should work.
You can simply create a package inside the main source, and incluse your images in this package. Then, just call the images in your main class like:
ImageIcon a = new ImageIcon(MainClass.class.getResource("/Package/Image.jpg"));
JFrame f = new JFrame("Edit Configure File");
//Image image = ImageIO.read(getClass().getResource("images/ctx.Icon"));
f.setIconImage(new ImageIcon("images/ctx.PNG").getImage());//this works for me finally
//f.setIconImage(image);
//f.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/ctx.PNG")));

Netbeans Built .jar doesn't work with class file inside

I had problems while finding the path of file(s) in Netbeans..
Problem is already solved (checked answer).
Today I noticed another problem: When project is finished,
I have to execute the generated .jar to launch the program, but it doesn't work because an error occurs: NullPointer (where to load a file) when accessing/openning jar outside Netbeans.
Is it possible to open a file with the class file in Java/Netbeans which works in Netbeans and even in any directory?
I've found already some threads about my problem in site but none was helpful.
Code:
File file = new File(URLDecoder.decode(this.getClass().getResource("file.xml").getFile(), "UTF-8"));
The problem you have is that File only refer to files on the filesystem, not files in jars.
If you want a more generic locator, use a URL which is what getResource provides. However, usually you don't need to know the location of the file, you just need its contents, in which case you can use getResourceAsInputStream()
This all assumes your class path is configured correctly.
Yes, you should be able to load a file anywhere on your file system that the java process has access to. You just need to have the path explicitly set in your getResource call.
For example:
File file = new File(URLDecoder.decode(this.getClass().getResource("C:\\foo\\bar\\file.xml").getFile(), "UTF-8"));

Regarding Help File in JAVA

I'm new to help file creation in java. I have created a help file "sample.chm" with a 3rd party tool, added it to a java program with package name as "help" calling with runtime class and build the jar. When I run the jar file it is giving me an error that the "file cannot be found, null pointer Exception". I have given a relative path to identify the file like "../help/sample.chm" still it is not working and I tried with various classes to ientify the path. But still the same error.
Request you to please help me in fixing it.
The jar can be placed in different systems and should open this help file with out any issues.
I hope my explanation is sufficient you to identify the problem.
Regards,
Chandu
If you have a file inside a jar, you can't access it as you normally would. You can access it like this:
URL helpFile=Thread.currentThread().getContextClassLoader().getResource("help/sample.chm");
The method used above (getResource) will return a URL; if you want, you can get it as an InputStream as well by using getResourceAsStream instead.
At least a workaround unless a better solution pops up. Use the this.getClass().getClassLoader().getResource way to get an inputstream to the help file inside the jar.
Copy the bytes to a new help file in the target systems temp folder and use this extracted file with the external help file viewer.

Categories

Resources