Showing posts with label Streams. Show all posts
Showing posts with label Streams. Show all posts

Streams: Basic I/O in Java

A stream represents a flow of data, or a channel of communication with a writer at one end and a reader at the other. To handle input and output we use java.io package. Let us discuss the classification of I/O streams.

Classification of I/O streams
  1. Byte Streams
  2. Character Streams
  3. Buffered Streams
  4. Terminal I/O or Console I/O
  5. Data Streams
  6. Object Streams
1. Byte Streams:

The byte streams are used to perform input and output of 8 – bit bytes. All byte stream classes are derived from InputStream and OutputStream

InputStream and OutputStream are abstract classes that define the lowest-level interface for all byte streams. They contain methods for reading or writing an unstructured sequence of bytes.
Java implements subclasses of these for activities such as reading from and writing to files. Because all byte streams inherit the structure of InputStream or OutputStream, the various kinds of byte streams can be used interchangeably. 

All the methods of this class will throw an IO Exception. Some of the byte streams are
 


2. Character Streams:

The Character Streams are used for reading or writing a sequence of character data, with support for Unicode. All other character streams in Java are built on top of Reader and Writer. Reader and Writer are very much like InputStream and OutputStream, except that they deal with characters instead of bytes. As true character streams, these classes correctly handle Unicode characters. InputStreamReader and OutputStreamWriter are special classes that use a character-encoding scheme to translate between character and byte streams.

All the methods of this class will throw an IO Exception. Some of the byte streams are




OutputStreamWriter


3. Buffered Streams:

A buffer can increase efficiency by reducing the number of physical read or write operations that correspond to read( ) or write( ) method calls. 

Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

Some of the buffered streams are

BufferedInputStream

BufferedOutputStream

BufferedReader

BufferedWriter

4. Terminal I/O or Console I/O

The terminal or console refers to command line environment or command prompt. The most commonly used standard output is System.out and System.err is derived from OutputStream object and standard input is System.in is derived from InputStream object. The following example shows the correspondence. 

FileInputStream in Java

The FileInputStream class is specially designed to work with byte – oriented input from the files. The FileInputStream is derived from abstract class InputStream. FileInputStream class can throw FileNotFoundException when its unable find input file.
Let us look a simple example of FileInputStream to read byte streams from the file as illustrated below.

Example:

//From FileInputStreamExample.java

import java.io.FileInputStream;

/**
 *
 * @author JavaHotSpot
 */

public class fileInputStreamExample
{
  public static void main(String args[])
  {
      try
      {
      int size;
      FileInputStream fi = new FileInputStream("C:\\file.txt");
      size=fi.available();
      System.out.println("The available bytes ="+size);
      byte[] bt=new byte[1000];
      fi.read(bt);
      System.out.println("File Content is =\n"+ new String(bt,0,size));
      fi.close();
   
      }
      catch(Exception ex)
      {
          System.err.println(ex);
      }

  }
}

Output:
The available bytes =177
File Content is =
A stream represents a flow of data,
or a channel of communication with a
writer at one end and a reader at the other.

FileOutputStream in Java

The FileOutputStream class is used to write data, byte by byte to a file. The FileOutputStream is derived from abstract class OutputStream.  It can throw FileNotFoundException or SecurityException. We need to remember that creation of FileOutputStream is not dependent on the file that already exists. In fact FileOutStream will create the file before opening it for output. If we attempt to open a read only file the throw an IOException. The return type of FileOutputStream is void.

Example:

//From fileOutputStreamExample.java

import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 *
 * @author JavaHotSpot
 */

public class fileOutputStreamExample
{
  public static void main(String args[])
  {
      try
      {
        String s1= "This is example of fileoutputstream class";
        byte[] data=s1.getBytes();  // Converts string into bytes
        byte[] indata=new byte[1000];
        int n=data.length;
        int size;
        System.out.println("Writing data, byte by byte...");
        FileOutputStream fo=new FileOutputStream("C:\\file1.txt");
        for(int i=0;i<n;i++)
        {
            fo.write(data[i]);
        }
        System.out.println("Writing is Done...!");
        fo.close();
        System.out.println("Reading....");
        FileInputStream fi=new FileInputStream("C:\\file1.txt");
        size=fi.available();
        fi.read(indata);
        System.out.println("File Content is =\n"+new String(indata,0,size));
        fi.close();

      }
      catch(Exception ex)
      {
          System.err.println(ex);
      }
  }
}


Output:
Writing data, byte by byte...
Writing is Done...!
Reading....
File Content is =
This is example of fileoutputstream class

InputStreamReader in Java

InputStreamReader is used to read keys from the keyboard, initially we construct an InputStreamReader stream from System.in and then use the InputStreamReader class’s read method to read what the user has typed. InputStreamReader class is derived from the Reader class.

The following example just read keys from the keyboard and displays them.

Example:

/**
From InputStreamReaders.java
*/

import java.io.InputStreamReader;

/**
 *
 * @author JavaHotSpot
 */
public class InputStreamReaders
{
  public static void main(String args[])
  {
      try
      {
          int ch;
         
          InputStreamReader ins=new InputStreamReader(System.in);
         
          while((ch=ins.read())!=-1)
          {
              System.out.print((char)ch);
          }
      }
      catch(Exception ex)
      {
          System.err.println(ex);
      }
  }
}


Output:
Hello from java

FileReader in Java

The FileReader class is used to create a character based stream that reads from file. The FileReader class is inherited from InputStreamReader and this will throw a FileNotFoundException

Let us look at the following example that will open the text file and reads the content and display it.

Example:

/**
From FileReaderExample.java
*/

import java.io.FileReader;

/**
 *
 * @author JavaHotSpot
 */

public class FileReaderExample
{
    public static void main(String args[])
    {
        try
        {
            char ch[]=new char[1000];
            int size;
            FileReader fr= new FileReader("C:\\file1.txt");
            size=fr.read(ch);
            System.out.println("File Content is \n"+new String(ch,0,size));
            fr.close();

        }
        catch(Exception ex)
        {
            System.err.println(ex);
        }
    }

}

Output:
File Content is