【问题标题】:Feedback form each time overwrites one text file with new incoming data每次反馈表都会用新的传入数据覆盖一个文本文件
【发布时间】:2012-03-06 07:04:24
【问题描述】:
<html>
  <head>
    <title>JSP Form</title>
    <style>
    </style>
  </head>
  <body>
    <form action="TestFileHandling.jsp" method="post">
      <fieldset>
        <legend>User Information</legend>
        <label for="question">Question</label>
        <input type="text" name="question"/><br/>
        <input type="submit" value="submit">
      </fieldset>
    </form>
  </body>
</html>

上面是一个简单的表单,让用户在发送问题之前输入问题。

<%@page import="myPackage.FileReaderWriter" %>
<%@page import="java.util.Vector" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
    Vector<String[]> v = new Vector<String[]>();
    String[] str1 = {request.getParameter("question")};
    v.addElement(str1);
    FileReaderWriter.saveVectorToFile(v, "MyTestFile.txt");
%>
<%
    Vector<String[]> vec = FileReaderWriter.readFileToVector("MyTestFile.txt");
    for (int i = 0; i < vec.size(); i++) {
        out.print("|");
        for (int j = 0; j < vec.elementAt(i).length; j++) {
            out.print(vec.elementAt(i)[j] + "|");
        }
%>
<br>
<%
    }
%>
</body>
</html>

这部分将输入的问题保存到文本文件中,然后打开文件以显示其中的内容。

这一切都是通过以下java代码完成的:

package myPackage;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

public class FileReaderWriter {
    public static void saveVectorToFile(Vector<String[]> v, String sFileName) {
        try {
            // Create a new file writer
            FileWriter writer = new FileWriter(sFileName);

            // Loop through all the elements of the vector
            for (int i = 0; i < v.size(); i++) {
                // Capture the index of the last item of each array
                int lastIndex = v.elementAt(i).length - 1;
                // Loop through all the items of the array, except
                // the last one.
                for (int j = 0; j < lastIndex; j++) {
                    // Append the item to the file.
                    writer.append(v.elementAt(i)[j]);
                    // Append a comma after each item.
                    writer.append(',');
                }
                // Append the last item.
                writer.append(v.elementAt(i)[lastIndex]);
                // Append a new line character to the end of the line
                // (i.e. Start new line)
                writer.append('\n');
            }
            // Save and close the file
            writer.flush();
            writer.close();
        }
        // Catch the exception if an Input/Output error occurs
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Vector<String[]> readFileToVector(String sFileName) {
        // Initialise the BufferedReader
        BufferedReader br = null;

        // Create a new Vector. The elements of this Vector are String arrays.
        Vector<String[]> v = new Vector<String[]>();
        try {
            // Try to read the file into the buffer
            br = new BufferedReader(new FileReader(sFileName));
            // Initialise a String to save the read line.
            String line = null;

            // Loop to read all the lines
            while ((line = br.readLine()) != null) {
                // Convert the each line into an array of Strings using
                // comma as a separator
                String[] values = line.split(",");

                // Add the String array into the Vector
                v.addElement(values);
            }
        }
        // Catch the exception if the file does not exist
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        // Catch the exception if an Input/Output error occurs
        catch (IOException ex) {
            ex.printStackTrace();
        }
        // Close the buffer handler
        finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        // return the Vector
        return v;
    }
}

我的问题是,尽管一切似乎都正常,但每次我输入一个新问题时,文本文件中的旧问题都会被覆盖。有没有办法解决这个问题,这样每次我在表单中输入一个新问题时,它都会与所有其他问题一起添加到文本文件中,而不是不断覆盖它?感谢您提供任何信息或帮助。

【问题讨论】:

    标签: java html forms file jsp


    【解决方案1】:

    尝试使用启用了append 选项的构造函数:

    FileWriter writer = new FileWriter(sFileName, true);
    

    【讨论】:

    • 我讨厌答案如此简单。哈哈,非常感谢大家。
    【解决方案2】:

    你需要以追加模式打开文件:

    FileWriter writer = new FileWriter(sFileName, true);
    

    这是FileWriter API 上的 Java 文档。

    【讨论】:

      【解决方案3】:

      FileWriter 有一个构造函数,可让您指定是否要附加到文件,例如

      // Create a new file writer
      FileWriter writer = new FileWriter(sFileName, true);
      

      【讨论】:

        【解决方案4】:

        打开文件进行追加就足够了——默认是重写文件:

        public static void saveVectorToFile(Vector<String[]> v, String sFileName) {
            // Create a new file writer
            FileWriter writer = new FileWriter(sFileName, true);
            // the rest of your code
        }
        

        【讨论】:

          猜你喜欢
          • 2014-11-18
          • 2010-12-14
          • 2022-08-07
          • 2018-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-21
          • 1970-01-01
          相关资源
          最近更新 更多