Java Streams


A stream is a path traveled by data in a program. To bring in information a program opens a stream on an information source (a file, memory, a socket) and reads the information serially.

Similarly a program can send information to an external destination by opening a stream to a destination and writing the information out serially.

Depending upon the direction of the data, streams are classified into TWO categories:
1) Input Streams
2) Output Streams

Input Stream

Input Streams: Bringing Information in.To bring in information, open a stream on an information source (a file, memory, or socket) and read the information serially.


Output Stream:

Output Stream:Sending Information Out. A program can send information to an external destination by opening a stream to a destination and writing the information out serially.


Stream classification:

Depending upon data type on which they operate, Java streams are classified into 2 categories:

Stream Classes:

  • The java.io package contains a large number of stream classes that provide capabilities for processing all types of data.
  • These classes may be categorized into two groups based on the data type on which they operate.
  • Byte Stream Classes: Byte Stream Classes are classes that provide support for handling i/o operations on bytes.
  • Character Stream Classes: Character Stream Classes are classes that provide support for managing i/o operations on characters.

Byte Stream Classes:

Byte stream classes have been designed to provide functional features for creating and manipulating streams and files for reading and writing bytes. Since the streams are unidirectional they can transmit bytes in only one direction and therefore java provides two kinds of bytes stream classes i.e. input stream classes and output stream classes.

Input Stream Classes:

Input stream classes that are used to read 8 bit bytes, include a super class known as InputStream and a number of subclasses for supporting various input related functions.


Output Stream Classes:

Output stream classes are derived from the base class OutputStream. This is an abstract class and has several subclasses and these subclasses can be used for performing output operations.



File Streams:
These handle writing and reading bytes to/from files.

FileInputStream:
A FileInputStream can be created with the FileInputStream (String constructor). The string argument should be the name of the file. After you create a file input stream you can read bytes from the stream by calling its read() method. This method returns an integer containing the next byte in the stream. If the method returns a -1 it signifies that end of the file stream has been reached.

Click here for example.

File Output Stream:
A file output stream can be created with FileOutputStream (String Constructor). The string argument should be the name of the file.

Note: You have to be careful when specifying the file to which to write an output stream. If it is the same as an existing file, the original contents will be lost when you start writing data to the stream.

You can create a FileOutputStream that appends data after the end of an existing file with the FileOutputStream (String, Boolean) constructor. The string specifies the file and the Boolean argument should equal to true to append data instead of overwriting any existing data.

The file output streams write (int) method is used to write bytes to the stream. After the last byte has been written to the file the streams close() method closes the stream.

Click here for example.

Character Stream classes:

  • Character stream classes can be used to read and write 16 bit Unicode characters.
  • Reader Stream class: Used to read characters from file. These are functionally same as InputStream classes but these read characters instead of bytes.
  • Writer Stream class: Used to write characters to file. These are functionally same as OutputStream classes but these write characters instead of bytes.

Reading/Writing Characters:

The Reader and Writer implement the streams that can handle characters. The two subclasses used for handling characters in files are FileReader and FileWriter.

            

Data Streams:

These are Filter streams used to read/write primitive data types instead of raw bytes.

To read primitives: DataInputStream.

To write primitives: DataOutputStream.

DataInputStream and DataOutputStream:

  • If you want to work with data that is not represented as bytes or characters you can use DataInputStream and DataOutputStream. These streams filter an existing byte stream so that each of the following primitive types can be read or written directly from the stream i.e. Boolean, byte, double, float, int, long and short.
  • The data input stream is created with the DataInputStream( Input Stream) constructor. The argument should be an existing input stream such as an buffer input stream or file input stream. Conversely, a data output stream requires a DataOutputStream (Output Stream) constructor which indicates the associated output stream.
  • Each of the input method returns the primitive data type indicated by the name of the method.
  • For example, readDouble() method returns a double value.

Click here for example 1.

Click here for example 2.

Using Data Streams:

DataInputStream dis = new DataInputStream(fis);

char c = dis.readChar();

byte b = dis.readByte();

Similarly,

DataOutputStream dos =new DataOutputStream(fos);

dos.writeChar(c );

dos.writeByte(b);

Character Strings:

Character strings are used to work with any text that is represented by ASCII value set or Unicode. Examples of files you can work with through a character stream are plain text files, html documents and java source files. The classes used to read and write these streams are subclasses of readers and writers. These should be used for all text input instead of dealing directly with file streams.

Reading Text Files

FileReader Stream
FileReader is the main class used when reading character streams from a file. This class inherits from InputStreamReader, which reads a file stream and converts the byte in integer value that represents Unicode characters. In the program given below the FileReader character stream is nested with BufferedReader stream because with character stream you can read one character at a time. But with BufferedReader you can read a line of text at a time using its ReadLine() method.

Click here for example.

Writing Text Files:

FileWriter Stream
The FileWriter class is used to write character streams to a file. It is a subclass of OutputStreamWriter which has a behavior to convert Unicode character codes to bytes.

There are two FileWriter constructors. They are FileWriter (String) and FileWriter (String, Bollean). The string indicates the name of the file that the character string will be directed into which can include a folders path also. The optional Boolean argument should be equal to true if the file is to be appended to a existing text file. The example given below in WriteCharFile.java reads the contents from ReadCharFile.java and writes into the file test.txt. // You can directly use the names of the file in FileReader and FileWriter.

Note: There are two ways of initializing the file stream objects. All of the constructors require that we provide the name of the file either directly or indirectly by giving a file object that is already been assigned filename.

Click here for example.

Interactive Input

Reading the Input through the keyboard

  • The system class contain three i/o objects, namely System.in, System.out and System.err where in, out and err are static variables. The variables in is of InputStream type and other two are of PrintStream type. We can use these objects to input from the keyboard, output to the screen and display error messages. System class is stored in java.lang package which is imported into java program automatically.

Click here for example.

  • To perform keyboard input for primitive data types we need to use the objects of DataInputStream and StringTokenizer classes. In the above program, KbdRead.java the first line of code wraps din over the input stream object System.in thus enabling object din to read from the keyboard.
  • The method call din.readLine() will fetch an entire string (upto a new line which will be discarded) from the console.
  • The statement st = new StringTokenizer(din.readLine()) initialized StringTokenizer object st with the string read by the readLine() method.
  • Int number = Integer.parseInt (st.nextToken()); takes the string, converts it into corresponding integer value and then assigns the result to the integer type variable number. Similar algorithm may be used for reading all other primitive data types from the console.

Using a Stream:

  • Import the package java.io , which contains a collection of stream classes.
  • Create an object of input/output stream that is associated with the data source / destination.
  • Read/write data using this object's read/ write methods.
  • Finally close the stream by calling its close() method.
Predefined standard streams
  • System.in - Keyboard input
  • System.out - Display output
  • System.err - Error stream

Programs

import java.io.*;
public class OutBytes
{
  public static void main (String args[])
  {
    int data[] = {65,66,67,68,69};
    try
    {
      FileOutputStream file = new FileOutputStream ("test");
      for(int i =0;i<data.length;i++)
      {
        file.write(data[i]);
      }
      file.close();
    }
    catch(IOException e)
    {
      System.out.println("Error");
    }
  }
}

import java.io.*;
public class InputBytes
{
  public static void main (String args[])
  {
    try
    {
      FileInputStream file = new FileInputStream ("test");
      boolean eof = false;
      int count = 0;
      while (!eof)
      {
        int in_put = file.read();
        System.out.print(in_put +" ");
        if(in_put==-1)
          eof = true;
        else
          count++;
      }
      file.close();
      System.out.println("\nTotal number of bytes read "+count);
    }
    catch(IOException e)
    {
      System.out.println("Error");
    }
  }
}


Exception Handling << Previous

Next>> Interfaces

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus












Footer1