0

I have looked at countless forum posts and articles on how to write to files, but to no avail have I come across a useful one. I use, currently, a FileWriter declared with:

   public FileWriter filewriter;

and then initated with

   try {
      filewriter = new FileWriter(textfile, true);
   } catch (IOException e) {
      e.printStackTrace();
   }

and then I write to the file with:

   try {
      filewriter.write(string + "string");
      filewriter.flush();
   catch (IOException e) {
      e.printStackTrace();
   }

So how do I make it so that my writer willl NOT overwrite the current text, and WILL add new lines to the text.

For example (Try to use these as an example): I want to write the following

  1. Go to the town
  2. Then turn right
  3. Then go into the tavern
  4. Say hi to the old man in purple

So how do I do that writing COMPLETELY from Java. All instigated at different times, like whenever you click a button, the first line writes, whenever you click it again, it writes the second line, and so on.

Zathen
  • 9
  • 1
  • 2
  • hint, look at `filewriter.flush();` – Caffeinated Feb 17 '13 at 00:09
  • 2
    http://www.mkyong.com/java/how-to-append-content-to-file-in-java/ googled that shit bro! – Savlon Feb 17 '13 at 00:10
  • 1
    There is nothing wrong with the code you have posted. If it's not appending to the file you're doing something wrong somewhere else. – Brian Roach Feb 17 '13 at 00:16
  • As an addition, here is a useful resource from javapractices.com: [Reading and writing text files](http://www.javapractices.com/topic/TopicAction.do;jsessionid=DA76D7A644E9CEFA70215CBBD192E7A8?Id=42) – informatik01 Feb 17 '13 at 00:16
  • @Savlon While you did google that, it still doesn't provide my answer. It doesn't write on a new line. – Zathen Feb 17 '13 at 00:54
  • 1
    As @BrianRoach said, the code is fine and something must be wrong elsewhere. You use the overloaded constructor to set the append mode. You are flushing. Please post the full code for your class (or method). – Philip Tenn Feb 17 '13 at 01:14

1 Answers1

0

The code as written is correct. It writes data at the end of the file with overwriting any existing data.

The only possible issue is that if the last line of the existing file does not end with a line terminator, then the first line of extra data that you write at the end will be appended to the and of the previous last line. If that is your concern, then the simple fix is to start by appending an empty line; e.g. filewriter.write(newline); where newline contains the appropriate line termination character or characters.

(I also notice that you "code" for writing does not include an explicit line terminator. Is it part of the string? Might that be your problem? The Writer.write(...) methods don't add line terminators automatically ...)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216