6

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?

Ben
  • 1,106
  • 1
  • 9
  • 17

5 Answers5

7

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

David Rabinowitz
  • 29,904
  • 14
  • 93
  • 125
5

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
  • 12,177
  • 6
  • 40
  • 66
2

As of apache FileUtils 2.1 you have this method:

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

Fred Haslam
  • 8,873
  • 5
  • 31
  • 31
1

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)

Kris
  • 51
  • 4
  • Simply posting an external link for an answer isn't appropriate for SO. Try explaining it. – sparkhee93 Feb 02 '16 at 04:28
  • 1
    Thanks @sparky. Left it that way as java official documentation was simple and self explanatory. However edited my answer now. – Kris Feb 02 '16 at 09:55
0

you could do something like

List x = FileUtils.readLines(file);
x.add(String)
FileUtils.writelines(file,x);
andrewsi
  • 10,807
  • 132
  • 35
  • 51