0

I am using the following to write StringBuilder into an existing text file.

FileUtils.writeStringToFile(file, sb.toString(), StandardCharsets.UTF_8);

The problem is that it overwrites the file where I just want to append sb.toString() to the existing content of file. How to workaround this issue?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Jacki
  • 95
  • 2
  • 8
  • 1
    Take a look at [the API docs](http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html), one line down from `writeStringToFile(File file, String data)` is `writeStringToFile(File file, String data, boolean append)` – azurefrog Apr 29 '16 at 17:35
  • Maybe this answer will help you. http://stackoverflow.com/a/1625263/5758826 – TubbyStubby Apr 29 '16 at 17:38

3 Answers3

4

It has been implemented in 2.1 version of Apache IO. To append string to the file just pass true as an additional parameter in functions:

example:

 FileUtils.writeStringToFile(file, stringBuilder.toString(), true);
Raj K
  • 458
  • 2
  • 7
  • 22
1

Assuming you're referring to org.apache.commons.io.FileUtils, there's an overloaded variant that takes a boolean append parameter:

FileUtils.writeStringToFile(file, sb.toString(), StandardCharsets.UTF_8, true);
// Here -----------------------------------------------------------------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Simply call the method with the append boolean:

writeStringToFile(File file, String data, Charset encoding, boolean append)

FileUtils.writeStringToFile(file, sb.toString(), StandardCharsets.UTF_8, true);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118