Java Append to File with FileWriter

FileWriter class is used for writing streams of characters. FileWriter takes an optional second parameter: append. If set to true, then the data will be written to the end of the file.

Java Append to File with FileWriter

This example appends data to a file with FileWriter. Let's create a sample.txt file under "src/main/resources" folder and add some content to it. Now, below program will append "Append some data" string to "sample.txt" file.
import java.io.FileWriter;
import java.io.IOException;

public class JavaAppendFileFileWriter {
    
    public static void main(String[] args) throws IOException {
        
        String fileName = "src/main/resources/sample.txt";
        
        try (FileWriter fw = new FileWriter(fileName, true)) {
            
            fw.append("Append some data\n");
        }
    }
}








Comments