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");
As your resource is bundled into the WAR, you can access it via the classloader. Ensure that the resource is bundled into your WEB-INF/classes folder. Show activity on this post. Show activity on this post.
You need to use -c switch of jar, to create the war file. Go inside the project directory of your project (outside the WEB-INF), then write the following command: jar -cvf projectname. war *
The location for WAR files is the webapps directory within your Tomcat installation directory.
class file is part of a Jar file, you can place the new version of the Jar file directly in application_root/module_name/WEB-INF/lib.” In Example. war file ,the WEB-INF/lib contains only three jar files(mysql-connector-java-5.0.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With