Java Append to File with Files Class

Java 7 introduced java.nio.file.Files class, which can be used to easily append data to a file.

Java append to file with Files

This example appends data with Files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class JavaAppendFileFiles {
    
    public static void main(String[] args) throws IOException {
        
        String fileName = "src/main/resources/sample.txt";
        
        byte[] tb = "Ramesh \n".getBytes();
        
        Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);
    }
}
The third parameter of Files.write() tells how the file was opened for writing. With the StandardOpenOption.APPEND, the file was opened for appending.
Files.write(Paths.get(fileName), tb, StandardOpenOption.APPEND);

Comments