getResources() returns null - java

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

Related

getClass() getResource returning null

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.

NullPointerException on an existing path

I get a problem while creating a Classifier. My existing path to it causes a NullPointerException. I am working with OpenCV 2.4.11 in Eclipse. The OS is Windows that's why I added another backslash between folders. When I insert the path with single backslashes in a file explorer it opens the XML File correctly. My code looks like this:
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
System.out.println("\nRunning FaceDetector");
String path = "C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
System.out.println("path:" + path);
CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource(path).getPath());
The output is:
Running FaceDetector
path:C:\Users\Juergen\OpenCV\opencv\sources\data\haarcascades\haarcascade_frontalface_alt.xml
Exception in thread "main" java.lang.NullPointerException
at FaceDetector.main(FaceDetector.java:24)
The code is based on the following instruction.
Any ideas on why the NullPointerException is thrown are appreciated.
Thanks
When we look at the Java API wi find this:
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-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
Therefore you must add a '/' in front of your absolute path:
String path = "/C:\\Users\\Juergen\\OpenCV\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
And you also should get rid of the windows file separator. Java understands the unix file separator and knows how to handle that on a windows system:
String path = "/C:/Users/Juergen/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";
I replaced my string by Yours, nothing changed. Still get a NullPointerException. The check
if (!new File(path).exists()) { throw new FileNotFoundException("Yikes!");}
does not throw any Exception – Jürgen K
Then from the *.class.getResource(path) you get an URL and from the URL's getPath() method you get a String which should most likely be the same as your original string.
Did you try to use it directly (with the leading '/')?

adding image in java swing [duplicate]

I need to get a resource image file in a java project. What I'm doing is:
URL url = TestGameTable.class.getClass().
getClassLoader().getResource("unibo.lsb.res/dice.jpg");
The directory structure is the following:
unibo/
lsb/
res/
dice.jpg
test/
..../ /* other packages */
The fact is that I always get as the file doesn't exist. I have tried many different paths, but I couldn't solve the issue.
Any hint?
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
leading slash to denote the root of the classpath
slashes instead of dots in the path
you can call getResource() directly on the class.
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
if you are calling from static method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

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.

How to get the right file path in Servlet program?

I am trying to read xml and txt file using relative path,
I tried getServletContext().getContextPath();
but it gets the path in a wrong way
for example
My file path is :
D:\dev\workspace\Simulater\src\resources\Map.xml
Now when I apply,
System.out.println(getServletContext().getContextPath());
I get as an output:
/Simulater
and when i apply :
File myTestFile= new File(Api.CONTEXT_PATH+fileName);
String path = myTestFile.getAbsoluteFile().toString();
System.out.println(path);
i get D:\Simulater\src\resources\Map.xml
an it is a wrong path since it dose not contains
:\dev\workspace\
it seams like java takes the project name and add the driver that contains it
so dose any one can provide any help to get the right path
thanx
use getServletContext().getRealPath("/") to get full path D:\dev\workspace\Simulater\src\resources\ then you can read file by giving this full path and file name.
To read a file you nead to open an InputStream, as your file is in your classpath you can open the stream with the following statement :
InputStream is = this.getClass().getResourceAsStream("/Map.xml");

Categories

Resources