I have no special talent. I'm only passionately curious - Albert Einstein
getResource and getResourceAsStream Comment on getResource and getResourceAsStream 0

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");


0 comments

Comments are currently disabled

About

David Malone is a Java developer residing in the Twin Cities area.  He has been developing enterprise applications since 2004.  This is his personal blog, as well as his design and development workspace.