getClass() getResource returning null - java

When I try and load a image from a resource directory in eclipse I keep getting a null pointer exception (NPE).
The res folder is in the project directory.
This where I get the NPE:
image.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("res/bg.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));
When I remove the getClass().getReource() the image is returned:
image.setIcon(new ImageIcon(new ImageIcon(("res/bg1.jpg")).getImage().getScaledInstance(image.getWidth(), image.getHeight(), Image.SCALE_SMOOTH)));
When I print the URL for the res directory I get null:
URL resource = this.getClass().getResource("/");
resource.getFile(); // print me somehwere
URL resource1 = this.getClass().getResource("/res");
resource.getFile(); // print me as well
URL resource2 = this.getClass().getResource("res/bg2");
resource.getFile(); // print me as well
System.out.println("Reource1 : " + resource);
System.out.println("Reource1 : " + resource1);
System.out.println("Reource1 : " + resource2);
Output:
Reource1 :file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
Reource1 : null
Reource1 : null
I have refreshed, cleaned, and built the project several times.
Directory:
Any idea why this is happening?
Thanks

Replace this.getClass().getResource("res/bg.jpg") with this.getClass().getResource("../res/bg.jpg")
Since this.getClass().getResource("/") returns file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/, you need to go one level(directory) up in the directory structure so that you can enter the res directory. It's like cd ../res from the current location of file:/C:/Users/cmooney/eclipse-workspace/TextSimplifier/bin/
Note: I can't see bg.jpg in the screenshot that you have attached. Make sure, you have bg.jpg in this path.

From the official java doc: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.String).
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

I think, you got the directory structure wrong.
If '/' points to the bin directory, as shown by the output of your first resource, '/res' points to the res subdirectory of bin and not to the sibling in the parent directory of bin.
You need to either move the res directory or change the way the resolution of '/' works.
The rules for searching resources associated with a given class are
implemented by the defining class loader of the class.
from Java documentation
For maven based projects the resource directory is usually src/main/resources.

Related

java.lang.NullPointerException when using getClass().getResource() to load an image [duplicate]

I am trying to load an image to use as an icon in my application. The appropriate method according to this tutorial is:
protected ImageIcon createImageIcon(String path, String description)
{
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
So, I placed the location of the file, and passed it as a parameter to this function. This didn't work, i.e. imgURL was null. When I tried creating the ImageIcon by passing in the path explicitly:
ImageIcon icon = new ImageIcon(path,"My Icon Image");
It worked great! So the application can pick up the image from an explicitly defined path, but didn't pick up the image using getResources(). In both cases, the value of the path variable is the same. Why wouldn't it work? How are resources found by the class loader?
Thanks.
getClass().getResource(path) loads resources from the classpath, not from a filesystem path.
You can request a path in this format:
/package/path/to/the/resource.ext
Even the bytes for creating the classes in memory are found this way:
my.Class -> /my/Class.class
and getResource will give you a URL which can be used to retrieve an InputStream.
But... I'd recommend using directly getClass().getResourceAsStream(...) with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.
In short: try using getResourceAsStream and some constructor of ImageIcon that uses an InputStream as an argument.
Classloaders
Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon was capable of finding it.
Edit: classpath
getResource is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.
As a noobie I was confused by this until I realized that the so called "path" is the path relative to the MyClass.class file in the file system and not the MyClass.java file. My IDE copies the resources (like xx.jpg, xx.xml) to a directory local to the MyClass.class. For example, inside a pkg directory called "target/classes/pkg. The class-file location may be different for different IDE's and depending on how the build is structured for your application. You should first explore the file system and find the location of the MyClass.class file and the copied location of the associated resource you are seeking to extract. Then determine the path relative to the MyClass.class file and write that as a string value with "dots" and "slashes".
For example, here is how I make an app1.fxml file available to my javafx application where the relevant "MyClass.class" is implicitly "Main.class". The Main.java file is where this line of resource-calling code is contained. In my specific case the resources are copied to a location at the same level as the enclosing package folder. That is: /target/classes/pkg/Main.class and /target/classes/app1.fxml. So paraphrasing...the relative reference "../app1.fxml" is "start from Main.class, go up one directory level, now you can see the resource".
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../app1.fxml"));
Note that in this relative-path string "../app1.fxml", the first two dots reference the directory enclosing Main.class and the single "." indicates a file extension to follow. After these details become second nature, you will forget why it was confusing.
getResource by example:
package szb.testGetResource;
public class TestGetResource {
private void testIt() {
System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
System.out.println("test2: "+getClass().getResource("test.css"));
}
public static void main(String[] args) {
new TestGetResource().testIt();
}
}
output:
test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
getResourceAsStream() look inside of your resource folder. So the fil shold be placed inside of the defined resource-folder
i.e if the file reside in /src/main/resources/properties --> then the path should be /properties/yourFilename.
getClass.getResourceAsStream(/properties/yourFilename)

How do I read images that are not saved in the same package as the class in which i need to use them?

For example, if I'm using this way for getting the images:
InputStream imgpacman2up = Tablero.class.getResourceAsStream("pacmanup1.png");
BufferedImage pacman2upImg = ImageIO.read(imgpacman2up);
pacman2arriba = new ImageIcon(pacman2upImg).getImage();
How would the route of the image ("In this case "pacmanup1.png") would be modified if the images are saved in a folder from another package of the project?
Thanks!
Quoting javadoc of getResourceAsStream():
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
Supposing that your image is in the package aaa.bbb.ccc use the following /aaa/bbb/ccc.
If it is within some folder named "resources" in src, then the below code accesses the image from your java class.
InputStream imgpacman2up = SampleTable.class.getResourceAsStream("/resources/pacmanup1.png");
BufferedImage pacman2upImg = ImageIO.read(imgpacman2up);
pacman2arriba = new ImageIcon(pacman2upImg).getImage();
If it is within some other package then the below code accesses the image from your java class.
InputStream imgpacman2up1 = SampleTable.class.getResourceAsStream("/com/abc/ab/pacmanup1.png");
BufferedImage pacman2upImg1 = ImageIO.read(imgpacman2up1);
pacman2arriba1 = new ImageIcon(pacman2upImg1).getImage();

Launching a text file from a .jar file (File path?)

I'm trying to launch a text file from a .jar file using Desktop.getDesktop().open(file)
String fileName = "file.txt";
URL url = getClass().getResource(fileName);
File fileToRead = new File(url.toURI());
Desktop.getDesktop().open(fileToRead);
I omitted the try-catch blocks for simplicity.
It is able to open my file when run from eclipse. But once I export to a .jar file, I get a NullPointerException in File fileToRead = new File(url.toURI());
When you package a class in a .jar file, it usually makes it nested one level deeper.
Therefore, you can try changing the first line to:
String filename = "../file.txt";
Looking at the JavaDoc of Class.getResource(String):
an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.'.
Parameters:
name - name of the desired resource
Returns:
A URL object or null if no resource with this name is found
Your resource was not found, hence NullPointerException. Specify the path within the JAR as described by the JavaDoc (absolute path starting with '/' or relative to the class of this, the object where you are calling getClass().getResource(fileName)) and you should get it.

getResources() returns null

Using Eclipse IDE. The line:
getClass().getResource("/res/bitmaps/image.png");
returns null. I have created the res folder in the root of my project.
The code of interest is:
bImage = ImageIO.read(getClass().getResource("/res/bitmaps/image.png"));
and it throws the exception:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1378)
at com.example.game.resource.Resources._loadImage(Resources.java:31)
at com.example.game.GameComponent.<init>(GameComponent.java:19)
at com.example.game.GameFrame.<init>(GameFrame.java:8)
at com.example.game.GameFrame.main(GameFrame.java:13)
Any help?
ImageIO.read(getClass().getResourceAsStream("res/drawable/image.png"));
Make sure res folder is in class path, verify using project properties > Java build Path > Source tab. If not in class path, can add via Add Folder.. button on the right.
You say the resource is in "the root of my project" - is it that folder in your build path? You need to have it in your build path so that Eclipse will copy it to the output directory (bin by default).
getClass().getResource("/res/drawable/image.png");
You should give the path of the folder in which image.png exists
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
package_name/name
Where the package_name is the package name of this object with '/' substituted for '.' ('\u002e').

ServletContext getResource not working

I'm trying to use ServletContext.getResource to retrieve a java.net.url reference to an image file (which I will then include in a PDF library using iText).
When I use ServletContext.getRealPath("picture.jpg"), I get back a string URL. However, getResource always returns null.
Example 1:
String picture = ServletContext.getRealPath("picture.jpg");
// picture contains a non-null String with the correct path
URL pictureURL = ServletContext.getResource(picture);
// pictureURL is always null
Example 2:
URL pictureURL = ServletContext.getResource("picture.jpg");
// pictureURL is always null
So what is the correct way to build a java.net.URL object pointing to a file in my webapps/ folder? Why does getRealPath work but not getResource?
In case it helps at all, here is my folder structure
webapps -> mySite -> picture.jpg
Does my picture need to be stored in either WEB-INF or WEB-INF/classes to be read by getResource?
Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root.
So you must provide the context-relative full path. For example:
URL pictureURL = servletContext.getResource("/images/picture.jpg");
(note the lower-cased servletContext variable)
getRealPath() provides the operating specific absolute path of a resource, while getResource() accepts a path relative to the context directory, and the parameter must begin with a "/". Try ServletContext.getResource ("/picture.jpg") instead.
Doc:
getResource

Categories

Resources