Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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);

As of apache FileUtils 2.1 you have this method:

static void write(File file, CharSequence data, boolean append)

There is an overload for FileUtils.writelines() which takes parameter on whether to append.

public static void writeLines(File file,
          Collection<?> lines,
          boolean append)
                   throws IOException

file - the file to write to

lines - the lines to write, null entries produce blank lines

append - if true, then the lines will be added to the end of the file rather than overwriting

Case1:

FileUtils.writeLine(file_to_write, "line 1");
FileUtils.writeLine(file_to_write, "line 2");

file_to_write will contain only

line 2

As first writing to the same file multiple times will overwrite the file.

Case2:

FileUtils.writeLine(file_to_write, "line 1");
FileUtils.writeLine(file_to_write, "line 2", true);

file_to_write will contain

line 1
line 2

The second call will append to the same file.

Check this from java official documentation for more details. https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#writeLines(java.io.File, java.util.Collection, boolean)

you could do something like

List x = FileUtils.readLines(file);
x.add(String)
FileUtils.writelines(file,x);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top