How do I read text file and output in Servlet?

后端 未结 2 472
孤城傲影
孤城傲影 2021-01-29 10:00

i have file: input.txt I want to read this file, put values in new output.txt from input.txt.

Servlet.java

protected void processRequest(HttpServletRequ         


        
相关标签:
2条回答
  • 2021-01-29 10:53

    Try following code

    input.txt should be present in the root directory of your application

    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();
            }
        }
    
    0 讨论(0)
  • 2021-01-29 10:55

    Apache FileUtils, could make it simple

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题