Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with filewriter overwriting files instead of appending to the end

OK, I'm having some trouble writing multiple lines to a text file.

the program runs, but it won't use new lines each time

when I want it run 4 times, the text file should look like:

a
b
c
d

instead, it looks like:

d

who knows how to fix this problem? all imports are correctly imported.

source(it's been slightly edited, assume everything is properly defined):

import java.io.*;
public class Compiler {
public static void main (String args[]) throws IOException
{
    //there's lots of code here
    BufferedWriter outStream= new BufferedWriter(new FileWriter("output.txt"));
    outStream.newLine();
    outStream.write(output);
    outStream.close();
}

}
like image 435
Azulflame Avatar asked May 29 '12 17:05

Azulflame


1 Answers

Make sure that when you create an instance of a FileWriter, that you are appending to the end of it. This can be done by using this specific FileWriter constructor which takes an additional boolean as a second parameter. This boolean tells the FileWriter to append to the end of the file, rather than overwriting the file.

BufferedWriter outStream= new BufferedWriter(new FileWriter("encoded.txt", true));
like image 190
nicholas.hauschild Avatar answered Nov 15 '22 14:11

nicholas.hauschild