Java program to write data into a file

Files are the most complicated concept in any programming language.In this tutorial we shall make it simpler by learning some basic techniques in File.There are two types of operation done on files.First, we can write the data into the file.The other operation is reading the data from the file.We shall go in detail now..

To write the data into a file we use the class FileOutputStream and the methods defined in that class.To utilize the methods defined in this class we need to create the objects for this class.There is a constructor defined for this class and the general form of this constructor is
FileOutputStream(String filepath);
For creating an object we use the following syntax.

FileOutputStream fis = new FileOutputStream("name_of_the_file");

With this we have created the objects for the class,now we need to invoke the suitable method defined in the class for writing the data.For this we use the method write() with the data to be wrote has a parameter.The main step in using the FileOutputStream is,whenever we are writing the data we need to convert the data into bytes.

import java.io.*;
class fileswritedemo
{
	public static void main(String arg[])
		{
			try
			{
	  			String str="I Love Java Programming";
				byte b[] = str.getBytes();
				FileOutputStream fos = new FileOutputStream("fi.txt");
				for(int i=0;i<b.length;i++)
				{
					fos.write(b[i]);
				}
				fos.close();
			}
			catch(Exception e)
			{
				System.out.print(e);
			}
		}
}

Output:
fileswritedemo

fileswritedemo2

Click here to download the program

Advertisements

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 Master's in Computer Science.
This entry was posted in Java and tagged , , , , , , , . Bookmark the permalink.

2 Responses to Java program to write data into a file

  1. Pingback: Creating and Writing Excel file in Java | letusprogram...!!!

  2. Pingback: Copying data from one file to other file using java | letusprogram...!!!

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 )

Google+ photo

You are commenting using your Google+ 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