Null pointer exception on getResource - java

I ma new to this so I am sorry if this is a stupid question. But please I need your help. I have the following directories in ecplise: Directory Hierarchy of course with a directory containing all these files.
I am trying to use get class.getResource to access a file called "data.txt" as such:
scanObj = new Scanner(new File(this.getClass().getResource("resources/data.txt").toExternalForm()));
But I am getting a null pointer exception why is that?
Many thanks!
Any help would be much appreciated

First print value of
this.getClass().getResource("resources/data.txt")
to console. If it prints null then that's the cause of problem.
This will mostly happen if the file that you are referring to is not on the class path.
Search for posts regarding how to add files to class path in eclipse.

Because the lookup is relative to the working folder of the application. Check what that folder is (should be in the run configuration for your class in Eclipse), and construct the path relative to that location.
Alternatively, use ClassLoader.getSystemClassLoader().getResourceAsStream("data.txt") (this will net you the InputStream)

Related

reading a text file from within a Jar on a remote device

Having researched this issue extensively here & elsewhere, without finding a working solution, I thought I'd ask...
I have a jar file (deployed on a RaspberryPi), with an internal structure like this:
myApp
MyClass
....
textFiles
foo.txt
....
I need 'MyClass' to read 'foo.txt'.
the general advice here & elsewhere is to use something like the following:
InputStream in = getClass().getResourceAsStream("../textFiles/foo.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
I have also read that the path to use (as the param for getResourceAsStream()) is the path to the target file, relative to the location of the class reading the file.(..?)
However, regardless of the path I use, I cannot get the above 2 lines to work. I always get an NPE thrown by the 2nd line.
I'm assuming that the NPE indicates that 'in' is null because 'foo.txt' has not been found.
any advice leading to a successful resolution, gratefully received.
cheers
Paul
Try removing the .. from the path, as per documentation:
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').
So my immediate problem has been solved, but not to my satisfaction.
I relocated the contents of 'textFiles' (in the Jar), so all the text files were in the Jar's root. I then successfully managed to find & load the file using:
InputStream in = getClass().getResourceAsStream("/foo.txt");
However, I still don't undserstand why this worked. I don't see why "/textFiles/foo.txt" didn't work, when the files were in that subdir, off the Jar's root...?
Anyway...I have a new problem now, which I think is hardware related....it takes about 40 seconds to read the files!! I think I blame the old SD card in my Raspberry Pi.
But that's a problem for another day!
Thanks for your input.

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

Save all files from a folder in a jar

First:
I know, this question was asked about 100 times already.
I know, someone already could have gave the right answer.
But anyway, I have to ask this again. I didn't found a solution working for me. sorry.
I'm writing a game in java. Of course I have many packages (folders) with sounds and pictures and so on. But these folders are each of variable size. So I want to save the content of such a folder dynamically in a list.
Usually, I was making this:
File f[] = new File(getClass.getResource("/home/res/").toURI()).listFiles();
Now I can iterate though this file object and save each file. Perfect. Really?
No. When I extract this Project into a jar archive, this fails. All because a uri isn't "hierarchical" or some stuff like this. See this exception:
C:\Users\Administrator\Desktop>java -jar Homework.jar
java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(Unknown Source)
at homework.moonface.src.Moonface.loadSounds(Moonface.java:94)
at homework.moonface.src.Moonface.<init>(Moonface.java:55)
at control.Overview.main(Overview.java:16)
Ok, I thought, so I need to get this path and add it manual into the file object. (new File("path"); But... this doesn't work. I'm getting the known error that the input wasn't written correctly, or when i try to cut of "file:" from the resource url, it breaks because in a jar its "jar:file:" and not "file:". But also if I cut of jar:file: I'm getting null.
So, please don't mark this as a duplicate, and try to explain this shortly for me. It would help thousand other, who don't understand other solutions who aren't solutions.
Try this :
URL jarResourceURL = getClass().getResource("/home/res/");
JarURLConnection jarURLConnection = (JarURLConnection) jarResourceURL.openConnection();
Enumeration<JarEntry> entries = jarURLConnection.getJarFile().entries();
while (entries.hasMoreElements()){
entries.nextElement(); // iterate over entries and do something
}
UPD: I was thinking about how spring framework's ClassPathXmlApplicationContext resolves the resources from jars. So i investigated the source code and foud that there is an utility class org.springframework.core.io.ClassPathResource which have a convenient interface (moreover there is a possibility to get the corresponding java.io.File instance using it) and can help you to solve the problem. Here is the doc :
http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/core/io/ClassPathResource.html

FileInputStream and FileNotFound Exception

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.
You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.
You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.
check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());
I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

getResource with parent directory reference

I have a java app where I'm trying to load a text file that will be included in the jar.
When I do getClass().getResource("/a/b/c/"), it's able to create the URL for that path and I can print it out and everything looks fine.
However, if I try getClass().getResource(/a/b/../"), then I get a null URL back.
It seems to not like the .. in the path. Anyone see what I'm doing wrong? I can post more code if it would be helpful.
The normalize() methods (there are four of them) in the FilenameUtils class could help you. It's in the Apache Commons IO library.
final String name = "/a/b/../";
final String normalizedName = FilenameUtils.normalize(name, true); // "/a/"
getClass().getResource(normalizedName);
The path you specify in getResource() is not a file system path and can not be resolved canonically in the same way as paths are resolved by File object (and its ilk). Can I take it that you are trying to read a resource relative to another path?

Categories

Resources