2

I have a java web application project that consists of a java servlet and then a classic java file. The servlet calls the methods implemented in the java file.

One of these methods involves reading from a file and putting the contents of that file into an array. However, after trying BufferedReader,InputStream and classloader.getResource(), I still can't seem to get it to be able to find the txt file.

In the Tomcat directory, the java files plus the txt file are located in /WEB-INF/classes. So I am not sure why it cant find the file..

Would anyone be able to tell me the best way of trying to read from that file?

Thanks in advance.

EDIT: This is my most recent attempt at trying to read from it, which resulted in the FileNotFound exception.

ClassLoader cl = testClass.class.getClassLoader();
File file = new File(cl.getResource("text.txt").getFile());

Scanner sc = new Scanner(file); 
Rachel Solomon
  • 167
  • 1
  • 13

2 Answers2

0

You can try this :

File file = new File(ClassLoader.getSystemResource("/path/to/file.txt").getFile());
Youssouf Maiga
  • 4,251
  • 5
  • 20
  • 34
  • thanks! just tried that and now theres no filenotfound error but a nullpointerexception error instead. Do you by chance have any idea why? – Rachel Solomon May 31 '17 at 15:58
0

Without leading /

ClassLoader cl = testClass.class.getClassLoader(); File file = new File(cl.getResource("text.txt").getFile());

text.txt should be in WEB-INF/classes/ppp/text.txt where ppp is package path of testClass.

With leading /

ClassLoader cl = testClass.class.getClassLoader(); File file = new File(cl.getResource("/text.txt").getFile());

text.txt is searched for on classpath (tomcat/lib, WEB-INF/lib, WEB-INF/classes, etc.).

Jeff Miller
  • 1,374
  • 1
  • 9
  • 18
  • Ooh thank you, I had actually tried the first part of your answer with text,txt in the correct location and it still had trouble finding the file. But I just realised I don't have a named package, its just (default package in eclipse). So I'm wondering could that be causing a problem? I'll try it also with the leading /. One question: When you say it is searched on the classpath. Does that mean it doesn't have a specific place to be, it could be in either of the directories you listed (i.e. tomcat/lib, WEB-INF/lib, WEB-INF/classes, etc.) ? – Rachel Solomon Jun 01 '17 at 08:22
  • I'm not sure all of the directories of tomcat's classpath but I know that the ones I listed are. Try creating logging file.getCanonicalPath() to see the exact path that is used. – Jeff Miller Jun 01 '17 at 12:59
  • I tried your leading / solution with my text file in the WEB-INF/classes directory and it worked for me! Thank you very much for your help!!!! – Rachel Solomon Jun 01 '17 at 13:05