简体   繁体   English

Java Web应用程序从文件读取并写入同一文件

[英]Java Web Application read from file and write to same file

Ok, I have a web application that I have written and I can read from a file that I have included in my source package in a new folder named "text". 好的,我已经编写了一个Web应用程序,并且可以从源程序包中包含的文件中读取一个名为“文本”的新文件夹。 I am trying to write to that same file, but it does not work. 我正在尝试写入相同的文件,但是它不起作用。 It never writes to the file. 它永远不会写入文件。 Here is the code for my two methods: 这是我的两种方法的代码:

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

If it matters, I am using NetBeans 如果有关系,我正在使用NetBeans

Use getServletContext().getRealPath("/") to get the current path of a web application 使用getServletContext().getRealPath("/")获取Web应用程序的当前路径

You Would better use this code that I have written right now 您最好使用我现在编写的这段代码

<%@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>

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. 部署后,将从war文件中读取该资源,甚至可能从war文件中的jar文件中读取。

Don't ever try to modify the contents of a webapp dynamically. 永远不要尝试动态修改Webapp的内容。 Even if it is possible, it's an extremely bad idea, since any redeployment of the webapp would delete the creted or modified files. 即使有可能,这也是一个非常糟糕的主意,因为对Web应用程序的任何重新部署都会删除经过创建或修改的文件。 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. 如果您必须在某个地方写,最好写一个数据库,因为它可以被多个webapp实例轻松共享,并且可以本地处理并发操作,也可以写一个webapp之外的文件。

BTW, the argument of the FileWriter constructor is a file path. 顺便说一句,FileWriter构造函数的参数是文件路径。 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). 因此, new FileWriter("/OBrien_PROJ2/text/catalog.txt")写入文件系统上的/OBrien_PROJ2/text/catalog.txt文件中(而不是在Webapp内部)。

First you will create two servlets. 首先,您将创建两个servlet。 Here I create A and B servlets. 在这里,我创建A和B servlet。

public class A extends HttpServlet { 公共类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();
        }
    }
}

here I write this text into addressBook.txt file.A servlet read the text file. 在这里,我将此文本写入addressBook.txt文件中.servlet读取了该文本文件。 B servlet write the text file. 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM