The Java FileOutputStream is an output stream for writing data to a File or to a FileDescriptor. It takes an optional second parameter, which determines whether the data is appended to the file.
Note that in the above example, we are passing a true parameter to FileOutputStream constructor.
Java Append to File with FileOutputStream
This example appends data to a file with FileOutputStream. 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.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class JavaAppendFileFileOutputStream {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = "src/main/resources/sample.txt";
byte[] tb = "Append some data \n".getBytes();
try (FileOutputStream fos = new FileOutputStream(fileName, true)) {
fos.write(tb);
}
}
}
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course