Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a text file in war archive [duplicate]

Tags:

java

jsf

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

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

I try 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

The problem however is that when I the method with the above code runs, A FileNotFoundException is thrown. I have also tried using the following line of code to get the file, but has not been successful

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

I still get the FileNotFoundException. How is this caused and how can I solve it?

like image 847
Seth IK Avatar asked Nov 06 '12 00:11

Seth IK


1 Answers

Try below:

   InputStream inputStream = 
      getClass().getClassLoader().getResourceAsStream("/resources/email/file.txt");
   BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream ));
like image 168
Yogendra Singh Avatar answered Oct 21 '22 20:10

Yogendra Singh