5

I am writing a Jersey Restful service to be deployed on Tomcat via a war file.

The service needs to read data in 3 text files. The text files need to exist on the file system or read from the classpath. I have tried to read the data from the file system and classpath but neither are working. I would be happy with either way - it doesn't matter.

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

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

I am getting a null pointer exception.

If I was to read the file from the file system, use the following code, where do I place the files in my Jar?

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

I am getting a FileNotFound exception.

Any suggestions are welcome.

Martin Matula
  • 7,969
  • 1
  • 31
  • 35
TheCoder
  • 8,413
  • 15
  • 42
  • 54

2 Answers2

4

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

Thanks all.

LaurentG
  • 11,128
  • 9
  • 51
  • 66
TheCoder
  • 8,413
  • 15
  • 42
  • 54
1

There is a similar thread in Java - Relative path of a file in a java web application.

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

Community
  • 1
  • 1
rlinden
  • 2,053
  • 1
  • 12
  • 13
  • I've tried that. I have been using every combination of paths and placing the file in different locations but my app cannot find the file. Can you give me an example of a path string and location? – TheCoder Jun 12 '12 at 10:20