Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can apache FileUtils.writeLines() be made to append to a file if it exists

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?

like image 798
Ben Avatar asked Oct 27 '09 09:10

Ben


2 Answers

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

like image 101
David Rabinowitz Avatar answered Sep 30 '22 09:09

David Rabinowitz


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);
like image 29
Markus Lausberg Avatar answered Sep 30 '22 09:09

Markus Lausberg