Appending data to the existing data in java

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:

file_append

Download the source code

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s