Can apache FileUtils.writeLines () be added to the file if it exists

The common FileUtils look pretty cool, and I cannot believe that they cannot be added to the file.

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

The above just replaces the contents of the file every time, and I would just like to mark this stuff as the code does.

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

I searched javadoc but found nothing! What am I missing?

+6
java append apache-commons java-io
source share
5 answers

You can use IOUtils.writeLines () , it gets a Writer object that you can initialize, as in your second example.

+7
source share

Now their method is like appendString (...) in the FileUtils class.

But you can get Outputstream from FileUtils.openOutputStream (...) and record it with

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

You can calculate off, so that you will reference the file.

EDIT

After reading Davids answer, I found out that BufferedWriter will do the job for you

 BufferedWriter output = new BufferedWriter(new FileWriter(simFile)); output.append(text); 
+5
source share

Like Apache FileUtils 2.1, you can use this method:

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

+1
source share

There is an overload for FileUtils.writelines () that takes a parameter to add.

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

file - file to write to

lines - lines for writing, zero records create empty lines

append - if true, then the lines will be added to the end of the file, but will not be overwritten

Option 1:

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

file_to_write will only contain

 line 2 

As soon as the first record in the same file overwrites the file several times.

Case 2:

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

file_to_write will contain

 line 1 line 2 

A second call will be added to the same file.

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

+1
source share

you can do something like

 List x = FileUtils.readLines(file); x.add(String) FileUtils.writelines(file,x); 
0
source share

All Articles