问题
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
.
来源:https://stackoverflow.com/questions/3888226/how-can-i-read-file-from-classes-directory-in-my-war