Read Write File In Java - Online Article

Introduction

This tutorial is an overview of Java I/O API. This tutorial assumes you have a basic knowledge of I/O, including InputStream and OutputStream. If you have training and experience in Java programmming, take this course to add to your knowledge.

In this tutorial, I provide example of code to show details "how to read and write a file". If you want to compile and run the same code and you do not have a Java compiler, you can download the Java Development Kit (JDK) from Sun Microsystems.

Input/output

Input is any information that is needed by your program to complete its execution. There are many forms that program input may take. Some programs use graphical components like a popup dialog box to accept and return the character string that is typed by the user. You are certainly familiar with programs that are controlled simply by clicking the mouse in a specific area of the screen. Still other programs, like word processing programs, get some of their input from a file that is stored on the computer's floppy or hard disk drive. Some programs, like web browsers, get their data from a network connection, while others get data from devices like scanners, digital cameras and microphones. The possibilities are limited only by computer scientists' imagination.

Output is any information that the program must convey to the user. The information you see on your computer screen is being output by one or more programs that are currently running on your computer. When you decide to print a document, a program is told to send some output to the printer. Any sound that your computer makes is because some program sent output to the speakers on your computer. The possibilities for program output are also limited only by our imaginations.

There are several potential error conditions that may occur when a program needs to get input from the user. If a user enters letters when a program is expecting numbers, an exception [error] will occur if the program assumes incorrectly that it has a valid integer to use in calculations. Programs must be written to survive bad input by the user. One way to do this is to ensure that only valid input is accepted. Standard Java classes do not ensure that only valid input is accepted. They are designed to be very flexible to support the wide variety of input and output options available now and in the future. This flexibility comes at the cost of increased complexity.

Java I/O

The java.io package contains a large number of classes, most of which are descended from InputStream or OutputStream. The stream classes define methods for reading and writing data from a variety of streams. In addition to stream I/O, java.io includes classes for file I/O and filename filtering (File, FilenameFilter, RandomAccessFile). The java.io package also includes a number of interfaces. Two of the more interesting interfaces are Serializable and Externalizable. The Serializable interface allows an object to write its state to a stream and read it back again. This is useful for passing objects as parameters in a distributed architecture (like RMI) and for making an object's state persistent. The Externalizable interface is also used for streaming objects, but the implementer has more control over the format and the contents of the stream.

Source Code

FileIOWriter.java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* * * @author Rajesh Kumar Gupta
* 		Computer Science & Engineering
*		Youth FOr Revolution, India
*		Built on Netbeans IDE 6.0
*/
public class FileIOWriter
{
	//Defining the file content to be written.
	String FileContent = "Youth For Revolution India: is a community founded by students of G.L.A. Institute "
							+ "of Technology and Management, Mathura (UP) India.";
	//Defining the OutputStream to write the file.
	OutputStream outputFile = null;
	//Creating the constructor to write the file.
	public FileIOWriter(String fileName)
	{
		try
		{
			//Defining the file name and initialize the FileOutputStream
			//to write the file.
			outputFile = new FileOutputStream(fileName);
			//Storing the charcters into the byte array.
			byte FileWriter[] = FileContent.getBytes();
			//Writing the file.
			for (int i = 0; i < FileWriter.length; i++)
			{
				outputFile.write(FileWriter[i]);
			}
		}
		//Catch the Exceptions.
		catch (IOException ex)
		{
			Logger.getLogger(FileIOWriter.class.getName()).log(Level.SEVERE, null, ex);
		}
		//Defining the final block to close the file after writing.
		finally
		{
			try
			{
				//Close the file after writing.
				outputFile.close();
			}
			catch (IOException ex)
			{
				Logger.getLogger(FileIOWriter.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}
	public static void main(String args[])
	{
		//Initializing the Constructer to write the file, with the name of file as parameter.
		new FileIOWriter("YFRIndia.txt");
	}
} 

FileIOReader.java

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* * * @author Rajesh Kumar Gupta
* 		Computer Science & Engineering
*		Youth FOr Revolution, India
*		Built on Netbeans IDE 6.0
*/
public class FileIOReader
{
	//Defining the constructor with the file name as parameter.
	public FileIOReader(String fileName)
	{
		//Defining the object of InputStream to read the file.
		InputStream input = null;
		try
		{
			//Initializing the InputStream object, with the file name as parameter.
			input = new FileInputStream(fileName);
			//Reads the text from InputStream, buffer them to read the content of file.
			BufferedReader inp = new BufferedReader(new InputStreamReader(input));
			//Printing the content of file.
			System.out.println(inp.readLine());
		}
		//Catching the Exceptions.
		catch (IOException ex)
		{
			Logger.getLogger(FileIOReader.class.getName()).log(Level.SEVERE, null, ex);
		}
		//Defining the final bloack to close the file after reading.
		finally
		{
			try
			{
				//Close the file after reading.
				input.close();
			}
			catch (IOException ex)
			{
				Logger.getLogger(FileIOReader.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}
	public static void main(String args[])
	{
		//Initializing the Constructer to read the file, with the name of file as parameter.
		new FileIOReader("YFRIndia.txt");
	}
}

About the Author:

No further information.




Comments

No comment yet. Be the first to post a comment.