Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read file from classes directory in my WAR?

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");
like image 553
newbie Avatar asked Oct 08 '10 06:10

newbie


People also ask

How do I read a file in a WAR file?

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.

How do I convert a directory to a WAR file?

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 *

Where are WAR files stored?

The location for WAR files is the webapps directory within your Tomcat installation directory.

How do I add a class file to WAR?

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.


1 Answers

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.

like image 72
Bozho Avatar answered Sep 30 '22 13:09

Bozho