How can I read file from classes directory in my W

2019-01-15 14:37发布

问题:

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

回答1:

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.