views:

45

answers:

1

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");
+5  A: 

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

getResourceAsStream("/my_filename.txt")

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

Bozho
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
@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
@newbie is the file for sure there? with the same name, extension and case?
Bozho
oops Bozho it should be `ServletContext context = getServletContext();``InputStream is = context.getResourceAsStream("WEB-INF/classes/my_filename.txt");` in my asnwer that i deleted. yours is correct +1
org.life.java
It started to work when I added /WEB-INF/classes/ to start of path. Thanx for help!
newbie