如何在Servlet中读取文本文件和输出?

时间:2013-12-15 11:11:40

标签: java servlets

我有文件:input.txt 我想读取这个文件,将值放在input.txt的新output.txt中。

Servlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition",
                 "attachment;filename=output.txt");
    PrintWriter out = response.getWriter();
    ServletContext cntxt = this.getServletContext();
    String fName = "/input.txt";
    InputStream ins = cntxt.getResourceAsStream(fName);
    try {
        if(ins != null){
        InputStreamReader isr = new InputStreamReader(ins);
        BufferedReader reader = new BufferedReader(isr);
        int n = 0;
        String word ="";
        while((word= reader.readLine())!= null)
         {
             n = Integer.parseInt(word);
             out.println(n);
         }
      } finally {
            out.close();
      }
}

但是output.txt为空。怎么了?

2 个答案:

答案 0 :(得分:0)

尝试以下代码

input.txt应出现在应用程序的根目录中

protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment;filename=output.txt");
        PrintWriter out = response.getWriter();
        ServletContext cntxt = this.getServletContext();
        String fName = "/input.txt";
        InputStream ins = cntxt.getResourceAsStream(fName);
        try {
            if (ins != null) {
                InputStreamReader isr = new InputStreamReader(ins);
                BufferedReader reader = new BufferedReader(isr);
                int n = 0;
                String word = "";
                while ((word = reader.readLine()) != null) {
                    n = Integer.parseInt(word);
                    out.println(n);
                }
            }
        }finally {
            out.close();
        }
    }

答案 1 :(得分:0)

Apache FileUtils,可以简化

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    List<String> lines = FileUtils.readLines(new File("file.txt), "UTF-8");

    for (String line : lines) {
        out.println(line);
    }
}