We can use the Guava library for appending to a file.
We need this Guava dependency:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
Java append to file with Guava
In the example, we append to a file with Guava's CharSink class.
import com.google.common.base.Charsets;
import com.google.common.io.CharSink;
import com.google.common.io.FileWriteMode;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
public class JavaAppendFileGuava {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/sample.txt";
File file = new File(fileName);
CharSink chs = Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
chs.write(" Appended Data \n");
}
}
The third parameter of Files.asCharSink() specifies the file writing mode; with FileWriteMode.APPEND option the file is opened for writing.
CharSink chs = Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course