Java append to file with Files

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/towns.txt";
        
        byte[] tb = "Žilina\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