Reading a text file in a military archive

I am trying to read a text file from my military archive and display the contents on the facelets page at runtime. My folder structure is as follows

+ war archive> + resources> + email> + file.txt

I am trying to read the file in the resources / email / file.txt folder using the following code

File file = new File("/resources/email/file.txt"); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } StringBuffer buffer = new StringBuffer(); if (reader != null) { String line = reader.readLine(); while (line != null) { buffer.append(line); line = reader.readLine(); // other lines of code 

However, the problem is that when I run the method with the above code, A FileNotFoundException . I also tried using the following line of code to get the file, but was not successful

 File file = new File(FacesContext.getCurrentInstance() .getExternalContext().getRequestContextPath() + "/resources/email/file.txt"); 

I am still getting a FileNotFoundException . How is this caused and how can I solve it?

+6
source share
4 answers

Try the following:

  InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/resources/email/file.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream )); 
+17
source

Try to avoid the file, as this is for reading things from the file system.

Since your resource is associated with a WAR, you can access it through the class loader.

Make sure that the resource is included in the WEB-INF / classes folder.

 InputStream in = new InputStreamReader(FileLoader.class.getClassLoader().getResourceAsStream("/resources/email/file.txt") ); 

This is a good blog about

http://haveacafe.wordpress.com/2008/10/19/how-to-read-a-file-from-jar-and-war-files-java-and-webapp-archive/

+8
source

If you want to get a Java file object, you can try the following:

 String path = Thread.currentThread().getContextClassLoader().getResource("language/file.xml").getPath(); File f = new File(path); System.out.println(f.getAbsolutePath()); 
+3
source

I prefer this approach:

 InputStream inputStream = getClass().getResourceAsStream("/resources/email/file.txt"); if (inputStream != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { ... } catch ... } else ... 

Three reasons:

  • it supports both: loading resources from an absolute path and from a relative path (starting from this class) - see also this answer
  • way to get the stream one step shorter
  • it uses a try-with-resources statement to implicitly close the main input stream
+1
source

All Articles