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

99封情书 提交于 2019-12-10 04:22:53

问题


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?


回答1:


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




回答2:


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



回答3:


As of apache FileUtils 2.1 you have this method:

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




回答4:


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)




回答5:


you could do something like

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


来源:https://stackoverflow.com/questions/1629713/can-apache-fileutils-writelines-be-made-to-append-to-a-file-if-it-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!