3
<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>

The above is a simple form that lets the user enter a question before sending it.

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

This part takes the question entered and saves it to a text file and then opens the file to display whatever is inside.

All this is done through the following java code:

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

My problem is that although everything seems to be working, everytime I enter a new question the old one in the text file gets overwritten. Is there a way I can fix this so that every time I enter a new question in the form, it will get added to the textfile along with all the others instead of constantly overwritting it? Thanks for any information or help.

JimmyK
  • 4,801
  • 8
  • 35
  • 47

4 Answers4

3

FileWriter has a constructor that lets you specify if you want to append to the file, e.g.

// Create a new file writer
FileWriter writer = new FileWriter(sFileName, true);
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
3

Try to use a constructor with an append option enabled:

FileWriter writer = new FileWriter(sFileName, true);
Community
  • 1
  • 1
Chetan
  • 1,507
  • 7
  • 30
  • 43
3

You need to open the file in append mode:

FileWriter writer = new FileWriter(sFileName, true);

Here is Java documentation on the FileWriter API.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
kosa
  • 65,990
  • 13
  • 130
  • 167
2

It should be enough to open the file for appending – the default is to rewrite files:

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
}
Community
  • 1
  • 1
millimoose
  • 39,073
  • 9
  • 82
  • 134