2

好的,我有一个我编写的 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

4

3 回答 3

3

用于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>

于 2013-04-20T20:39:26.957 回答
0

The resource you read is not a file. It's a resource loaded by the classloader. When deployed, this resource will be read from inside a war file, and perhaps even from a jar file inside this war file.

Don't ever try to modify the contents of a webapp dynamically. Even if it is possible, it's an extremely bad idea, since any redeployment of the webapp would delete the creted or modified files. If you have to write somewhere, write to a database (preferrably), since it can easily be shared by multiple webapp instances, and handle concurreny natively), or to a file outside of the webapp.

BTW, the argument of the FileWriter constructor is a file path. So new FileWriter("/OBrien_PROJ2/text/catalog.txt") writes to the file /OBrien_PROJ2/text/catalog.txt on the file system (and not inside the webapp).

于 2013-04-20T20:05:24.273 回答
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();
    }
}
于 2016-03-08T06:54:07.297 回答