views:

76

answers:

4

Every time I write to the text file I will lose the original data, how can I read the file and enter the data in the empty line or the next line which is empty?

public void writeToFile()
{   

    try
    {
        output = new Formatter(myFile);
    }
    catch(SecurityException securityException)
    {
        System.err.println("Error creating file");
        System.exit(1);
    }
    catch(FileNotFoundException fileNotFoundException)
    {
        System.err.println("Error creating file");
        System.exit(1);
    }

    Scanner scanner = new Scanner (System.in);

    String number = "";
    String name = "";

    System.out.println("Please enter number:");
    number = scanner.next();

    System.out.println("Please enter name:");
    name = scanner.next();

    output.format("%s,%s \r\n",  number, name);
    output.close();

}
+3  A: 

You must open the file for append.

Aaron Digulla
+1  A: 

You need to open myFile in append mode. See this link for an example.

bdonlan
A: 

We're you've got: new Formatter(myFile); you'll want to use new Formatter(new FileWriter(myfile, true). The true indicates you want to append to that file.

Tim
+1  A: 

As others have said, use the append option.

This code can write data in the default platform encoding:

  private static void appendToFile() throws IOException {
    boolean append = true;
    OutputStream out = new FileOutputStream("TextAppend.txt", append);
    Closeable resource = out;
    try {
      PrintWriter pw = new PrintWriter(out);
      resource = pw;
      pw.format("%s,%s %n", "foo", "bar");
    } finally {
      resource.close();
    }
  }

There are a number of classes you can wrap around an OutputStream to achieve the same effect. Be aware that the above approach can lose data when the code is run on a platform that doesn't use a Unicode default encoding (like Windows) and may produce different output on different PCs.

One case in which care is need is if the encoding inserts a byte order mark. If you wanted to write lossless Unicode text in UTF-16 marked with a little-endian BOM, you would need to check the file for existing data.

private static void appendUtf16ToFile() throws IOException {
  File file = new File("TextAppend_utf16le.txt");
  String encoding = (file.isFile() && file.length() > 0) ?
      "UnicodeLittleUnmarked" : "UnicodeLittle";
  boolean append = true;
  OutputStream out = new FileOutputStream(file, append);
  Closeable resource = out;
  try {
    Writer writer = new OutputStreamWriter(out, encoding);
    resource = writer;
    PrintWriter pw = new PrintWriter(writer);
    resource = pw;
    pw.format("%s,%s %n", "foo", "bar");
  } finally {
    resource.close();
  }
}

Supported encodings:

McDowell