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");
}
}
Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.
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.
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 / .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With