In real life we may encounter a situation in which may need to write the new data in a file without loosing old data.This is called as appending of data.We can make this using many classes present in the Java io package.In this post we shall make it using FileOutputStream class which we have used to write the data to a file.
One of the constructor of the FileOutputStream is:
FileOutputStream("Name_of_the_file",boolean);
We use this constructor with true as the value for boolean. If didn’t use the boolean value it will overwrite the data present in the file.In the following program I’m appending a string to the data present in the file.
import java.io.*; class fileappend { public static void main(String arg[]) { try{ FileOutputStream fos = new FileOutputStream("append.txt",true); String name = "\nThis is appended to the existing content....!!!"; byte b[] = name.getBytes(); for(int i=0;i<b.length;i++) fos.write(b[i]); } catch(Exception e) { System.out.print(e); } } }
Output: