Java Web Application从文件读取并写入同一文件

时间:2013-04-20 20:00:14

标签: java jsp netbeans

好的,我有一个我写过的Web应用程序,我可以从我的源包中包含的文件中读取一个名为“text”的新文件夹。我试图写入同一个文件,但它不起作用。它从不写入文件。以下是我的两种方法的代码:

public void fillItems() throws IOException{
    String path = "/OBrien_PROJ2/text/catalog.txt";
    BufferedReader br = new BufferedReader(new   InputStreamReader(getClass().getResourceAsStream(path))); 
    String text = null;
    while ((text=br.readLine())!=null){
       String[] itemArray = text.split(","); 
       // you might want to check array size
       items.add(new ItemBean (itemArray[0], itemArray[1], itemArray[2], itemArray[3], itemArray[4]));

    }

    br.close();
}



 public void createNewItem(String iD, String name, String description, String price, String quantity) throws IOException{
     String path = "/OBrien_PROJ2/text/catalog.txt";
     BufferedWriter bw = new BufferedWriter(new FileWriter(path));
     bw.write(iD + "," + name + "," + description + "," + price + "," + quantity);
     items.add(new ItemBean (iD, name, description, price, quantity));
     bw.flush();
     bw.close();
 }

如果重要,我正在使用NetBeans

3 个答案:

答案 0 :(得分:2)

使用getServletContext().getRealPath("/")获取Web应用程序的当前路径

您最好使用我现在编写的代码

<%@page import="java.io.BufferedOutputStream"%>
<%@page import="java.io.FileOutputStream"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <h1>Hello World!</h1>
    <%
        try{
        String file = getServletContext().getRealPath("/")+"text/test.txt";
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        bos.flush();
        bos.close();
        }
        catch(Exception ex){
            ex.printStackTrace();
            }
    %>
</body>

答案 1 :(得分:0)

您阅读的资源不是文件。它是由类加载器加载的资源。部署后,将从war文件内部读取此资源,甚至可以从此war文件中的jar文件中读取该资源。

不要试图动态修改webapp的内容。即使有可能,这也是一个非常糟糕的主意,因为任何webapp的重新部署都会删除creted或modified文件。如果你必须在某处写,请写入数据库(最好),因为它可以很容易地被多个webapp实例共享,并且本地处理concurreny),或者写入webapp之外的文件。

BTW,FileWriter构造函数的参数是文件路径。所以new FileWriter("/OBrien_PROJ2/text/catalog.txt")写入文件系统上的文件/OBrien_PROJ2/text/catalog.txt(而不是写在webapp中)。

答案 2 :(得分:0)

首先,您将创建两个servlet。在这里,我创建了A和B servlet。

公共类A扩展了HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        InputStream input= this.getClass().getResourceAsStream("addressBook.txt");
        int x= input.read();
        while(x != -1){
            char c= (char) x;
            out.print(c);
            x= input.read();                
        }
     }
        catch(Exception ex){
               ex.printStackTrace();
        }

        finally{
            out.close();
        }
    }
}

这里我将此文本写入addressBook.txt文件。一个servlet读取文本文件。 B servlet写文本文件。

public class B extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String name=request.getParameter("n");
        String mobile=request.getParameter("m"); 
        out.println(name+"<br>");
        out.println(mobile);
        FileWriter fileWriter=new FileWriter("E:\\IJSE\\ABSD\\DAY 6\\Assignment 1\\src\\java\\adbook.txt",true);
        PrintWriter printWriter=new PrintWriter(fileWriter,true);
        if(name==null||mobile==null) {
           } else {
                printWriter.println("<tr><td>" + name + "</td><td>" + mobile + "</td></tr>");
                out.println("<body bgcolor=\"#1589FF\">\n" +
                "<script language=\"javascript\">\n" +
                "alert( \"Added successfull\" );\n" +
                "</script>\n" +
                "<p></p>");

           }
        printWriter.close();
    }
}