如何将servlet中的列表写入.txt

时间:2014-10-28 17:16:55

标签: java servlets

我创建了一个servlet,它滚动了10个随机值排序并打印了这个值。此值将添加到LinkedList。当应用程序关闭时,如何将LinkedList数据保存到file.txt。我尝试在servlet中创建文件并写一些东西,但我的代码不是创建文件。

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet NewServlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet NewServlet at " + request.getContextPath() + "</h1>");
        List<Integer> lista=(List<Integer>) this.getServletContext().getAttribute("lista");
        out.println("<ul>");
        for(Integer l:lista){
            out.println("<li>"+l+"</li>");
        }
        out.println("</ul>");
        out.println("<form action=\"NewServlet1\">");
        out.println("<input type=\"text\" name=\"liczba\">");
        out.println("<input type=\"submit\" value=\"ADD\">");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    } finally {            
        out.close();
    }

        PrintWriter zapis = null;
        zapis = new PrintWriter("test.txt");
        zapis.println("type type type ");
        zapis.close();


}

public class NewServletListener implements ServletContextListener {

static final public String defFileName = "file.txt";
String fileName;

@Override
public void contextInitialized(ServletContextEvent sce) {
    List<Integer> lista=new LinkedList<Integer>();
    Random rand=new Random();
    int rozmiar=Integer.parseInt(sce.getServletContext().getInitParameter("rozmiar"));
    for(int i=0;i<rozmiar;i++){
        lista.add(rand.nextInt(100));
    }
    sce.getServletContext().setAttribute("lista", lista);

    fileName = sce.getServletContext().getInitParameter("SAVE_FILE");
    if (fileName == null) {
        fileName = defFileName;
    }
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
//        throw new UnsupportedOperationException("Not supported yet.");
        List<Integer> lista=(List<Integer>) sce.getServletContext().getAttribute("lista");

    File file = new File(fileName);
    try (PrintWriter printWriter = new PrintWriter(file)) {
        for (Integer l:lista) {
            printWriter.println(l);
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

}
}

很奇怪,但文件没有创建。我应该添加到web.xml SAVE_FILE吗?或者我做错了什么。 文件应该在我关闭重叠时创建吗?

1 个答案:

答案 0 :(得分:0)

好的,我假设您在Web应用程序中的某处计算List<String>存储为名为"lista"的servlet上下文属性。当应用程序停止到文本文件时,您希望保存它,每行一个字符串。

您必须使用ContextLoaderListener。假设你使用servlet 3.0+容器,你可以用注释注册它(如果没有,你必须在部署描述符web.xml中注册它。你只需用onDestroy方法编写文件:

@WebListener
public class SaveListener implements ServletContextListener {
    static final public String defFileName = "file.txt";
    String fileName;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // allow to find the name of the file in init parameters
        fileName = sce.getServletContext().getInitParameter("SAVE_FILE");
        if (fileName == null) {
            fileName = defFileName;
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        List<String> lista = (List<String>) sce.getServletContext()
                .getAttribute("lista");
        File file = new File(fileName);
        try (PrintWriter printWriter = new PrintWriter(file)) {
            for (String string : lista) {
                printWriter.println(string);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}