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

我有文件: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是空的。 怎么了?

请尝试以下代码

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(); } } 

Apache FileUtils可以使它变得简单

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); List lines = FileUtils.readLines(new File("file.txt), "UTF-8"); for (String line : lines) { out.println(line); } }