1/12/12

Advance I/O Streams in Java

A Stream is a flow of data from the source to a sink. Source and sink are also called input and output streams, respectively. 

The I/O Streams are of two Kinds :
1. Byte Streams 
2. Character Streams

Normally the term stream refers to the byte stream and the terms  reader and writer refer to the character stream.


Byte Streams


Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.

The InputStream Methods


int read()
int read(byte[] buffer)
int read(byte[] buffer,int offset, int lenght)


The first method returns an int, which contains either a byte read from the stream, or a -1, which indicates the end of file condition. The other two methods read the stream into a byte array and return the number of bytes read. 


Note :
For efficiency, always read data in the largest practical block.


void close()

When you have finished with a stream, close it. If you have a stack of streams, use filter streams to close the stream at the top of the stack. This operation also closes the lower streams.


int available ()

This method reports the number of bytes that are immediately to be read from the stream.

The OutputStream Methods


int write()
int write(byte[] buffer)
int write(byte[] buffer,int offset, int lenght)

void close()

When you have finished with a stream, close it. If you have a stack of streams, use filter streams to close the stream at the top of the stack. This operation also closes the lower streams.


void flush ()

Sometimes the stream accumulates writes before committing them. The flush() method enables us to force the writes.

Character Stream


The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.

All character stream classes are descended from Reader and Writer. As with byte streams, there are character stream classes that specialize in file I/O.

The Reader Method


int read()
int read(char[] cbuf)
int read(char[] cbuf, int offset, int length)

The first method returns an int, which contains either a byte read from the stream, or a -1, which indicates the end of file condition. The other two methods read the stream into a character array and return the number of bytes read.

void close() 
boolean ready()
long skip(long n)

The above methods are analogous to the input stream versions.

The Writer Method


void write(int c)
void write(char[] cbuf)
void write(char[] cbuf, int offset, int length)
void write(String string)
void write(String string, int offset, int length)

A Simple Example : 


The following code reads character from a file named 'text1.txt' and writes the character out to a file named 'text2.txt'. Thus, it copies the file. 

import java.io.*;

public class TestStreams{
  public static void main(String [] args){
    try {
       FileReader frObj = new FileReader("text1.txt");
       FileWriter fwObj = new FileWriter("text2.txt");   // If this file doesn't                                         exist, then the program will create one.
       char[] buffer = new char[128];
       int charRead;

       //Read 1st buffer
       charRead = frObj.read(buffer);
       while ( charRead != -1) {
          //write the buffer out to the Output file
           fwObj.write(buffer,0,charRead);
           //Read next buffer
          charRead = frObj.input(buffer);
       }
        frObj.close();
        fwObj.close();
        } catch( Exception e){
             e.printStackTrace();
        }
   }
}

Handling the buffer is tedious and error-prone, but Java has some predefined classes like BufferedReader which help us to read using the buffer and thus take care of all the errors and tediousness.

Buffered Stream : 

The below program also does what the above program does, but the difference is that this uses buffered streams instead of character streams. The advantage is that Buffered Stream read one line at a time unlike Character Stream which read one character at a time.


import java.io.*;

public class TestStreams{
  public static void main(String [] args){
    try {
       FileReader frObj = new FileReader("text1.txt");
       BufferedReader bfObj = new BufferedReader(frObj);
       FileWriter fwObj = new FileWriter("text2.txt");   
       BufferedWriter bwObj = new BufferedWriter(fwObj);
       String line;

      //Read 1st line
       line = bfObj.readLine();
       while ( line != null ) {
          //write the line out to the Output file
           bwObj.write(line,0,line.length);
           bwObj.newLine();
           //Read next line
          line = bfObj.readLine();
       }
        bfObj.close();
        bwObj.close();
        } catch( Exception e){
             e.printStackTrace();
        }
   }
}


  Article by Farhan Khwaja
Farhan has written 83 articles .
If you like This post, you can follow Code 2 Learn on Twitter.
Subscribe to Code 2 Learn feed via RSS or EMAIL to receive instant updates.
Want to write for Code 2 Learn. Read here for more info

SHARE THIS POST:

1 comment:

  1. Though Streams are good and provide a consistent way of reading and writing data.Biggest disadvantage of using Streams is that they are blocking call and can hinder performance, there synchrony alternatives java.nio and channel are much better for high performance application. I have also shared my view on Using memory mapped file for high performance IO, you may find useful.

    ReplyDelete