views:

621

answers:

2

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");
 }
}
+1  A: 

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.

tangens
THANK you ...please can you explain why it is not working with T.class.getClassLoader().getResourceAsStream..
Chris
If you use `Class.getResourceAsStream( name )`, `name` is resolved internally. "test.txt" is transformed into "my/package/test.txt" and "/test.txt" is transformed into "test.txt". Then `ClassLoader.getResourceAsStream()` is called with the transformed name. Your code should work with both methods, but you have to check that your file "test.txt" stays in the right place (inside your classpath). With your call, you have to put "test.txt" inside your top level package directory.
tangens
A: 

Hi there.. I am facing the same issue, that is getResourceAsStream() is returning null. I have to pass a full URI in that method, which exists, still I am getting this error. May be classpath is not set, but how can I set the classpath. I am using eclipse and using my own build.xml. I am not sure where shall I set the classpath. Please help