In my previous example I have explained about how to write to a file using the FileOutputStream. This example demonstrates how to append to an existing file without creating the new file. By default, FileOutputStream creates new file or overwrite when we try to write into a file. If you want to append with the existing content, then you have to use “append” flag in the FileOutputStream constructor. Lets look at the example below.
In the below example, FileOutputStream constructor second parameter set as “true” that is the flag for appending to the existing file. Hope this helps you to understand the append to existing content.
package javabeat.net.io; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Java Append OutputStream Example * * @author Krishna * */ public class AppendOutputStreamExample { public static void main(String args[]) throws IOException { String str = "Append OutputStream Example \n"; File textFile = new File("TextFile.txt"); FileOutputStream fileOutputStream = null; try { //Create FileOutputStream with append flag as true fileOutputStream = new FileOutputStream(textFile, true); // Writes bytes to the stream fileOutputStream.write(str.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // close the stream try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }