Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems using Class.getResourceAsStream() in Java

Tags:

java

I'm a bit stuck on a project I'm working on where I want to load in a text file from another folder. I'm using Netbeans, and have, for the purposes of this problem, two folders, one with my class in, and one with the resource in.

The class is in ../misc/[ClassName] and the text file I want to load is in ../resources/[Name].txt

This sounds unbelievably simple, and having done Java for quite a while I really should know this, I assumed the best way of loading this file rather than using just a FileReader, would be to use getResourceAsStream, as shown:

InputStream is = 
        this.getClass().getClassLoader().getResourceAsStream(_filename + ".txt");

Ideally saving me time and not having to hardcode in a filepath. Now, my problem is I constantly keep getting null returned from the above code, and indeed any other permutation I can put on it. I've tried /resource/filename.txt or resource/filename.txt as parameters, using .getClass().getResourceAsStream as opposed to getClassLoader(), everything is still returning the same result.

Just to avoid any confusion, I've checked the filename and its definitely right and in the right case etc. as well, so that isn't the issue. Any ideas? I know I could just use FileReader to accomplish the same goal, but its kind of a principle thing now!

like image 508
David Meadows Avatar asked Feb 18 '10 12:02

David Meadows


1 Answers

The class is apparently loaded by a different classloader which doesn't know about the resource at all. Rather use the context's ClassLoader obtained from the current Thread instead. It knows everything.

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(_filename + ".txt");
like image 183
BalusC Avatar answered Oct 13 '22 21:10

BalusC