I have no special talent. I'm only passionately curious - Albert Einstein
April 10, 2009
getResource and getResourceAsStream
Posted by Dave Malone
in Java,
Technology
This is so basic but it's also one of the most frustrating things to deal with in Java. On Windows, I was trying to load a file in a TestCase within my IDE. I know the way to do this is to use this.getClass().getClassLoader().getResource() and this.getClass().getClassLoader().getResourceAsStream(). I spent more time than I should have had to in order to figure out how to get this to work correctly. All examples and Javadocs I encountered stated that the solution should work in a completely different way. And there are tons of postings around the net with people asking for the answer to this problem, so here it is.
The file I'm loading is relative to the class that is loading it, i.e. my directory structure looks like this:
- com\mypackage\FileLoaderTest.java
- com\mypackage\test.txt
According to all other examples I have read, I should only have to load the file in my FileLoaderTest methods like this:
this.getClass().getClassLoader().getResourceAsStream("tests.txt");
Other sites I read state the same assumption, or even suggest building a path like this:
this.getClass().getClassLoader().getResourceAsStream("com/mypackage/tests.txt");
That didn't work either. What did end up working was this:
this.getClass().getClassLoader().getResourceAsStream("\\com\\mypackage\\tests.txt");
Comments are currently disabled