Posts Tagged java.io

Java I/O Stream

Tuesday, May 17th, 2011

By: Pankaj Yadav

It can be used to write the data on file. It provides us methods to perform various tasks on the file. In order to use this class we have to import java.IO package.

Syntax:

import java.io.*;

In this package we have input stream and output stream for read and write in a file.

Input Stream

The java.io.InputStream is the base class of the input streams in java .The input stream read data form a file with the help of read() method. The read() method returns integer type value. If read() method does not have any byte to read returns the -1.

Example:

InputStream inputs = new FileInputStream("c://data//file.txt");
int _idata = inputs.read();
while( _idata> -1 )
{
_idata = inputs.read();
}

Output Stream

The java.io.OutputStream is the base class of the output streams in java. The write() method is used to write the data in the file .

Example:

import java.io.FileOutputStream;
import java.io.OutputStream;

public class OutputStreamExample {

	public static void main(String[] args) {

		try{
			OutputStream out = new FileOutputStream("c://file.txt");
			out.write("testOutputstream".getBytes());
			out.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

}

We can also use these streams in the sequence to perform the different tasks. This class also provides the buffering techniques for faster performance.