Written by Sai Sandeep Thota on December 1, 2013 in Java > Programming

Java Program to Insert Data into a File using FileOutputStream

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this tutorial we will explain how to store / insert Data into a File. To perform file operations we will need FileInputStream and FileOutputStream of Byte stream class, they handle the files Byte-by-Byte. FileInputStream is used to read contents from a file and FileOutputStream is used to write contents to a file.

FileOutputStream creates a new file if the specified File doesn’t exist, if it already exists then the File is replaced with new content. To insert data into a file without rewriting it, we need to use FileWriter.

So what are we doing exactly in this program?
#1. FileOutputStream object is created specifying a File path.
#2. A String is defined and some value is given to that string.
#3. As FileOutputStream and FileInputStream handles Bytes, we need to create a byte array and get the bytes from our string using getBytes() method.
#4. We are using a for loop to iterate till b.length.
#5. Then write() method is used to write Byte array to the file.

Java Program to Insert Data into a File using FileOutputStream

/*
Download more at ProgrammingUnit.com
*/
import java.io.*;

class insertData {
	public static void main(String args[]) throws IOException {
		FileOutputStream fos = new FileOutputStream("file.txt");

		String str="ProgrammingUnit.com Rocks!";

		byte b[] = str.getBytes();

		for(int i=0;i<b.length;i++)
		{
			fos.write(b[i]);
		}
		
		fos.close();
		
		System.out.println("Data successfully written to File.");
	}
}

Download Source Code

Output:

Java Program to Insert Data into a File using FileOutputStream

The File (file.txt) :

file_java_FileOutputStream

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: