在war存档中读取文本文件 [英] Reading a text file in war archive

查看:112
本文介绍了在war存档中读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的war存档中读取文本文件,并在运行时在facelets页面中显示内容。我的文件夹结构如下:

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

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

我尝试使用以下代码读取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

然而问题是当我使用的方法时上面的代码运行,抛出了一个 FileNotFoundException 。我也尝试使用以下代码行来获取文件,但是没有成功

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");

我仍然得到 FileNotFoundException 。这是怎么造成的,如何解决?

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

推荐答案

试试以下内容:

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

这篇关于在war存档中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆