35

In my Maven project, I have a xls file in src/main/resources. When I read it like this:

 InputStream in = new
 FileInputStream("src/main/resources/WBU_template.xls");

everything is ok.

However I want to read it as InputStream with getResourceAsStream. When I do this, with or without the slash I always get a NPE.

     private static final String TEMPLATEFILE = "/WBU_template.xls";
     InputStream in = this.getClass.getResourceAsStream(TEMPLATEFILE);

No matter if the slash is there or not, or if I make use of the getClassLoader() method, I still get a NullPointer.

I also have tried this :

URL u = this.getClass().getResource(TEMPLATEFILE);
System.out.println(u.getPath());

the console says.../target/classes/WBU_template.xls and then get my NullPointer.

What am I doing wrong ?

dutchman79
  • 483
  • 2
  • 6
  • 13

2 Answers2

52

FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process.

getResourceAsStream() will load a file path relative from your application's classpath.

When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.

When you use .getClass().getClassLoader().getResource(fileName) it considers the location of the fileName is the root - in other words bin folder.

The file should be located in src/main/resources when loading using Class loader

In short, you have to use .getClass().getClassLoader().getResource(fileName) to load the file in your case.

Rahul
  • 15,979
  • 4
  • 42
  • 63
  • 1
    Thanks. This was clear so far. Problem is that in this way I still can not access the xls file in the src/main/resources folder. – dutchman79 Dec 20 '12 at 07:55
  • 1
    As I mentioned earlier, please try using .getClass().getClassLoader().getResourceAsStream(fileName) – Rahul Dec 20 '12 at 07:57
  • Also, remove the slash from your fileName. /WBU_template.xls => WBU_template.xls – Rahul Dec 20 '12 at 08:04
  • 4
    This works fine when I run the app from IDE, but when i compile application in to jar file its always looking for path myjar.jar!\myfile.txt. Any clue? – Yasitha Waduge Jun 27 '14 at 07:58
2

I usually load files from WEB-INF like this

session.getServletContext().getResourceAsStream("/WEB-INF/WBU_template.xls")
sainath reddy
  • 292
  • 1
  • 3
  • 13