8

I need to read text file from the classpath in Java WAR application. How can I read it as InputStream. File is located in /WEB-INF/classes/ folder, but when I use following code, it just returns null.

InputStream input = servletContext.getClass().getClassLoader().getResourceAsStream("my_filename.txt");
newbie
  • 23,730
  • 77
  • 197
  • 300

1 Answers1

11

Prefix it with a forward slash to denote the root of the classpath:

getResourceAsStream("/my_filename.txt")

Alternatively, you can use the serlvetContext.getResourceAsStream(..) which looks for resources relative to the context root. So classes would be /WEB-INF/classes.

Ravi K Thapliyal
  • 49,621
  • 9
  • 73
  • 89
Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
  • I tried with that too, but it still returns null. Does servletContext have right classloader or how can I be sure that I'm using right classloader ? – newbie Oct 08 '10 at 06:49
  • @newbie: . One trick is to write a file with the same name at the same location, if you can't read, and then see where exactly the program has written the file. – Adeel Ansari Oct 08 '10 at 06:57
  • @newbie is the file for sure there? with the same name, extension and case? – Bozho Oct 08 '10 at 07:06
  • It started to work when I added /WEB-INF/classes/ to start of path. Thanx for help! – newbie Oct 08 '10 at 07:18