views:

896

answers:

2

The commons FileUtils look pretty cool, and I can't believe that they cannot be made to append to a file.

File file = new File(path);
FileUtils.writeLines(file, printStats(new DateTime(), headerRequired));

The above just replaces the contents of the file each time, and I would just like to keep tagging this stuff to end just as this code does.

fw = new FileWriter(file, true);
try{
    for(String line : printStats(new DateTime(), headerRequired)){
        fw.write(line + "\n");
    }
}
finally{ 
    fw.close();
}

I've searched the javadoc but found nothing! What am I missing?

+2  A: 

Their is now method like appendString(...) in the FileUtils class.

But you can get the Outputstream from FileUtils.openOutputStream(...) and than write to it by using

write(byte[] b, int off, int len)

You can calculte the off, so that you will apend to the file.

EDIT

After reading Davids answer i recognized that the BufferedWriter will do this job for you

BufferedWriter output = new BufferedWriter(new FileWriter(simFile));
output.append(text);
Markus Lausberg
+5  A: 

You can use IOUtils.writeLines(), it receives a Writer object which you can initialize like in your second example.

David Rabinowitz