How to read a text file from a web application

I am writing a Restful Jersey service that will be deployed to Tomcat through a war file.

The service needs to read data in three text files. Text files must exist on the file system or read from the class path. I tried to read data from the file system and classpath, but none of them work. I would be happy anyway - it doesn't matter.

If the following code was used, can someone tell me where to place the specified text file so that the code picks up the file?

BufferedReader br = new BufferedReader(new InputStreamReader (this.getClass().getClassLoader().getResourceAsStream("myfile.txt"))); 

I get a null pointer exception.

If I were to read a file from the file system, use the following code, where should I put the files in my Jar?

 FileInputStream fs = new FileInputStream("myFile.txt"); DataInputStream is = new DataInputStream(fs); BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

I get a FileNotFound exception.

Any suggestions are welcome.

+4
source share
2 answers

I copied my text file to the WEB-INF/classes folder and used this.getClass().getClassLoader().getResourceAsStream("/myfile.txt") and it worked.

Thanks to everyone.

+4
source

There is a similar stream in Java - the relative path to a file in a java web application .

If you want to know the directory in real time, you can access the methods of the ServletContext class. I believe the getContextPath method may be useful to you.

+1
source

All Articles