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
  • 24,286
  • 80
  • 201
  • 301

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
  • 51,095
  • 9
  • 76
  • 89
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 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