-2

Is it possible to write text to a file without overwriting previous data?

What I have done always is:

StringBuffer sb = new StringBuffer();
BufferedReader in;
PrintWriter out;

try{
    in = new BufferedReader( new FileReader("somefile.txt"));
    out = new PrintWriter( new FileWriter("somefile.txt"));

    String input = "";
    while(input != null){
        sb.append(input + "\n");
        input = in.readLine();
    }
    in.close()

    out.print(sb.toString());

    // now start doing what I want.

Is this the correct way?

Mordechai
  • 15,437
  • 2
  • 41
  • 82

2 Answers2

2

Check out the FileWriter API. There's a constructor that accepts a boolean parameter -- you may wish to use it.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

You can use the append mode for FileWriter to avoid overwriting existing data:

new PrintWriter( new FileWriter("somefile.txt", true));
Reimeus
  • 158,255
  • 15
  • 216
  • 276