Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse getResourceAsStream returning null

I cannot get getResourceAsStream to find a file. I have put the file in the top level dir, target dir, etc, etc and have tried it with a "/" in front as well. Everytime it returns null.

Any suggestions ? Thanks.

public class T {
 public static final void main(String[] args) {

  InputStream propertiesIS = T.class.getClassLoader().getResourceAsStream("test.txt");

  System.out.println("Break");
 }
}
like image 737
Chris Avatar asked Feb 03 '10 21:02

Chris


People also ask

What is the difference between Class getResource () and Classloader getResource ()?

Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.

How does getResource work in Java?

The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java. net.

How do you send paths in getResourceAsStream?

getResourceAsStream , send the absolute path from package root, but omitting the first / . If you use Class. getResourceAsStream , send either a path relative the the current Class object (and the method will take the package into account), or send the absolute path from package root, starting with a / .

Should we close getResourceAsStream?

You should always close streams (and any other Closeable, actually), no matter how they were given to you. Note that since Java 7, the preferred method to handle closing any resource is definitely the try-with-resources construct.


2 Answers

Put your file "test.txt" into the same directory where the java file of your class is (same package). Then use

T.class.getResourceAsStream( "test.txt" );

This works, because eclipse automatically copies the file as a resource to the classpath. When using the command line, you have to do this by hand.

like image 54
tangens Avatar answered Sep 16 '22 14:09

tangens


You shouldn't need to add these files to the same directory to get it to work.

I was getting this symptom when I created a new Package and Source Folder to hold my junit tests. The tests would fail because getResourceAsStream was returning null.

Here's how to fix it:

Right-click the class (in my case, the new junit test class) in the Eclipse Project Explorer View

Build Path -> Configure Build Path -> Java Build Path -> Source Tab -> Add Folder

Select the folder that holds your files.

like image 34
Ben L. Avatar answered Sep 20 '22 14:09

Ben L.