I/O Stream Chaining


I/O stream classes are designed to work together via stream chaining.

It allow the creation of complex I/O processing in Java with the concept of chaining.

This means that an instance of one Stream is passed as a parameter to the constructor of another.

Each class performs a specific task on the data and forwards it to the next class in the chain. Stream chaining can be very useful.

Input Streams Classes Chaining

java fileio

Output Streams Classes Chaining

java fileio

Read Write Primitive Using Stream Chaining

Example
 
	import java.io.*;
	public class ChainDemo1
	{
	public static void main(String [] args)
	{
	try
	{
	FileOutputStream fos =new FileOutputStream("myfile.txt");
	BufferedOutputStream buffer =new BufferedOutputStream(fos);
	DataOutputStream dataOut =new DataOutputStream(buffer);
	dataOut.writeUTF("Hello!");
	dataOut.writeInt(4);
	dataOut.writeDouble(100.0);
	dataOut.writeDouble(72.0);
	dataOut.writeDouble(89.0);
	dataOut.writeDouble(91.0);
	dataOut.close();
	buffer.close();
	fos.close();
	}
	catch(IOException e)
	{
	e.printStackTrace();
	}
	}
	}

Example

	import java.io.*;
	public class ChainDemo2
	{
	public static void main(String [] args)
	{
	try
	{
	FileInputStream fis =new FileInputStream("myfile.txt");
	DataInputStream dis = new DataInputStream(fis);
	System.out.println(dataIn.readUTF());
	int counter = dis.readInt();
	double sum = 0.0;
	for(int i = 0; i < counter; i++)
	{
	double current = dis.readDouble();
	System.out.println("Read" + current);
	sum += current;
	}
	System.out.println("Avg" + sum/counter);
	dis.close();
	fis.close();
	}catch(IOException e)
	{
	e.printStackTrace();
	}
	}
	}