Low-level and high-level stream classes

 

Overview

At its lowest level, all Java I/O involves a stream of bytes either entering or leaving memory as shown by this diagram:

 

Memory

Output stream of bytes

External device

 
 
 
 
 
 

----->

  

     

<-----

 
 
 
 
 
 

Input stream of bytes

 

Obviously, sending and receiving individual bytes would be tedious and difficult for an application to manage. For that reason, several packaged classes exist that make it easy for a program to read and write larger units of data.

Most programs use a "high-level" stream class object that is "chained" (connected) to a "low-level" stream class object. While the low-level stream class object handles byte I/O, the high-level stream class object will allow the program to read and write primitive data values and even objects (as shown below).

 

Application

  

  

"High-level" stream class object

 

 

"Low-level" stream class object

 

  

External device

  

  

<--->

<--->

primitives and objects

bytes

  

 

There are many stream classes, but you will only be required to know the ones that are highlighted below:

 

Direction

Low-level classes

High-level classes

Output

ByteArrayOutputStream

FileOutputStream

BufferedOutputStream

DataOutputStream

ObjectOutputStream

PrintStream

Input

ByteArrayInputStream

FileInputStream

BufferedInputStream

DataInputStream

LineNumberInputStream

ObjectInputStream

PushbackInputStream

 

The FileOutputStream class

Object 

\

OutputStream

\

FileOutputStream

FileOutputStream out = new FileOutputStream(fd);

will construct a FileOutputStream object for sending bytes to the file. If the file already exists, its contents will be replaced (there is an overloaded constructor to specify appending). Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.

Method

Usage

close()

Closes the stream and releases stream resources

write()

Writes the right-most 8 bits of a specified integer value to the stream

Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.

import java.io.*;
public class App {
  public static void main(String[] args) {

    // Local variables and object references.

    char again = 'y';
    File fd;
    FileOutputStream out;

    // Get the path name from the user.

    System.out.print("Enter the file's complete path name: ");
    fd = new File(Keyboard.readString());

    // Try to write data to the output stream.

    try {

      // Open an output stream for the file.

      out = new FileOutputStream(fd);

      // This loop asks the user to enter a number and writes it to the
      // stream. The user is then asked if they want to enter another.

      while (again == 'Y' || again == 'y') {
        System.out.print("Enter a number: ");
        int theNumber = Keyboard.readInt();
        out.write(theNumber);
        System.out.print("Again? (Y/N): ");
        again = Keyboard.readChar();
      }

      // Close the stream.

      out.close();
      System.out.println("Closed - " + fd.getPath());
    }

    // Catch an IOException if one is thrown.

    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

 

The FileInputStream class

Object 

\

InputStream

\

FileInputStream

FileInputStream in = new FileInputStream(fd);

will construct a FileInputStream object for reading bytes from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.

Method

Usage

available()

Returns the number of bytes that can be read from this input stream

close()

Closes the stream and releases stream resources

read()

Reads the next byte value from the input stream

Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.

import java.io.*;
public class App {
  public static void main(String[] args) {

    // Local variables and object references.

    File fd;
    FileInputStream in;

    // Get the path name from the user.

    System.out.print("Enter the file's complete path name: ");
    fd = new File(Keyboard.readString());

    // Try to read data from the input stream.

    try {

      // Open an input stream for the file.

      in = new FileInputStream(fd);

      // This loop reads a byte from the stream and displays
      // its value. The loop ends when no more bytes are available.

      while (in.available() > 0) {
        System.out.println(in.read());
      }

      // Close the stream.

      in.close();
      System.out.println("Closed - " + fd.getPath());
    }

    // Catch an IOException if one is thrown.

    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

 

The DataOutputStream class

Object

\

OutputStream

   

\

FilterOutputStream

\

DataOutputStream

DataOutputStream out = new DataOutputStream(new FileOutputStream(fd));

will construct a DataOutputStream object chained to a FileOutputStream object for sending primitive values and UTF strings to the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.

Method

Usage

writeBoolean()

Writes a specified boolean value to the stream

writeByte()

Writes a specified byte value to the stream

writeChar()

Writes a specified char value to the stream

writeDouble()

Writes a specified double value to the stream

writeFloat()

Writes a specified float value to the stream

writeInt()

Writes a specified int value to the stream

writeLong()

Writes a specified long value to the stream

writeShort()

Writes a specified short value to the stream

writeUTF()

Writes a specified String to the stream according to the UTF standard

Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.

import java.io.*;
public class App {
  public static void main(String[] args) {

    // Local variables and object references.

    char again = 'y';
    File fd;
    DataOutputStream out;

    // Get the path name from the user.

    System.out.print("Enter the file's complete path name: ");
    fd = new File(Keyboard.readString());

    // Try to write data to the output stream.

    try {

      // Open an output stream for the file.

      out = new DataOutputStream(new FileOutputStream(fd));

      // This loop asks the user to enter a number and writes it to the
      // stream. The user is then asked if they want to enter another.

      while (again == 'Y' || again == 'y') {
        System.out.print("Enter any real number (n.n): ");
        double theNumber = Keyboard.readDouble();
        out.writeDouble(theNumber);
        System.out.print("Again? (Y/N): ");
        again = Keyboard.readChar();
      }

      // Close the stream.

      out.close();
      System.out.println("Closed - " + fd.getPath());
    }

    // Catch an IOException if one is thrown.

    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

 

The DataInputStream class

Object

\

InputStream

   

\

FilterInputStream

\

DataInputStream

DataInputStream in = new DataInputStream(new FileInputStream(fd));

will construct a DataInputStream object chained to a FileInputStream object for reading primitive values and UTF strings from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.

Method

Usage

readBoolean()

Reads a boolean value from the stream

readByte()

Reads a byte value from the stream

readChar()

Reads a char value from the stream

readDouble()

Reads a double value from the stream

readFloat()

Reads a float value from the stream

readInt()

Reads a int value from the stream

readLong()

Reads a long value from the stream

readShort()

Reads a short value from the stream

readUTF()

Reads a String from the stream according to the UTF standard

Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.

import java.io.*;
public class App {
  public static void main(String[] args) {

    // Local variables and object references.

    File fd;
    DataInputStream in;

    // Get the path name from the user.

    System.out.print("Enter the file's complete path name: ");
    fd = new File(Keyboard.readString());

    // Try to read data from the input stream.

    try {

      // Open an input stream for the file.

      in = new DataInputStream(new FileInputStream(fd));

      // This loop reads a double value from the stream and displays
      // it. The loop ends when end of file is reached.

      try {
        while (true) {
          System.out.println(in.readDouble());
        }
      }
      catch (EOFException e) {
        System.out.println("<END OF FILE>");
      }

      // Close the stream.

      in.close();
      System.out.println("Closed - " + fd.getPath());
    }

    // Catch an IOException if one is thrown.

    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

 

The ObjectOutputStream class

Object

\

OutputStream

 

\

ObjectOutputStream

public class Customer implements Serializable

The interface requires no methods.

Many packaged classes are serializable including all wrapper classes, String and Stringbuffer classes, Vector and Array classes, and the collection classes. In other words, an entire collection, such as a SortedMap, can be stored as an object on disk!

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fd));

will construct a ObjectOutputStream object chained to a FileOutputStream object for sending primitive values and serializable objects to the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.

Method

Usage

writeBoolean()

Writes a specified boolean value to the stream

writeByte()

Writes a specified byte value to the stream

writeChar()

Writes a specified char value to the stream

writeDouble()

Writes a specified double value to the stream

writeFloat()

Writes a specified float value to the stream

writeInt()

Writes a specified int value to the stream

writeLong()

Writes a specified long value to the stream

writeObject()

Writes a specified serializable object to the stream

writeShort()

Writes a specified short value to the stream

writeUTF()

Writes a specified String to the stream according to the UTF standard

Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.

import java.io.*;
public class App {
  public static void main(String[] args) {

    // Local variables and object references.

    char again = 'y';
    String[] array;
    File fd;
    ObjectOutputStream out;

    // Get the path name from the user.

    System.out.print("Enter the file's complete path name: ");
    fd = new File(Keyboard.readString());

    // Try to write data to the output stream.

    try {

      // Open an output stream for the file.

      out = new ObjectOutputStream(new FileOutputStream(fd));

      // This loop constructs an array with values entered by the user
      // and writes the array to the file. The user is given the option
      // of repeating the loop to construct and store another array.

      while (again == 'Y' || again == 'y') {
        System.out.print("How many strings will you enter? ");
        array = new String[Keyboard.readInt()];
        for (int i = 0; i < array.length; i++) {
          System.out.print("Enter a string: ");
          array[i] = Keyboard.readString();
        }
        out.writeObject(array);
        System.out.print("Again? (Y/N) ");
        again = Keyboard.readChar();
      }

      // Close the stream.

      out.close();
      System.out.println("Closed - " + fd.getPath());
    }

    // Catch an IOException if one is thrown.

    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

 

The ObjectInputStream class

Object

\

InputStream

 

\

ObjectInputStream

ObjectInputStream out = new ObjectInputStream(new FileInputStream(fd));

will construct a ObjectInputStream object chained to a FileInputStream object for reading primitive values and serializable objects from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.

Method

Usage

readBoolean()

Reads a boolean value from the stream

readByte()

Reads a byte value from the stream

readChar()

Reads a char value from the stream

readDouble()

Reads a double value from the stream

readFloat()

Reads a float value from the stream

readInt()

Reads a int value from the stream

readLong()

Reads a long value from the stream

readObject()

Reads an object from the stream

readShort()

Reads a short value from the stream

readUTF()

Reads a String from the stream according to the UTF standard

Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.

import java.io.*;
public class App {
  public static void main(String[] args) {

    // Local variables and object references.

    File fd;
    ObjectInputStream in;

    // Get the path name from the user.

    System.out.print("Enter the file's complete path name: ");
    fd = new File(Keyboard.readString());

    // Try to read data from the input stream.

    try {

      // Open an input stream for the file.

      in = new ObjectInputStream(new FileInputStream(fd));

      // This loop reads a array objects from the stream and displays
      // their contents. The loop ends when end of file is reached.

      try {
        while (true) {
          String[] array = (String[]) in.readObject();
          for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
          }
          System.out.println("<< END OF ARRAY >>");
        }
      }
      catch (EOFException e) {
        System.out.println("<< END OF FILE >>");
      }

      // Close the stream.

      in.close();
      System.out.println("Closed - " + fd.getPath());
    }

    // Catch an IOException if one is thrown.

    catch (IOException e) {
      System.out.println(e.getMessage());
    }

    // Catch an ClassNotFoundException if one is thrown.

    catch (ClassNotFoundException e) {
      System.out.println(e.getMessage());
    }
  }
}

 

Looking ahead

All the files in this lesson were sequential. The data was stored in a particular order and read in the same order. In the next lesson you will learn how to create and use a random access file in which an item of data may be read from or written to an existing file based upon its position within the file.

 

Review questions

  1. Which of the following provide a method for reading of an int value from a stream?  (choose two)

  1. ObjectInputStream

  2. FileInputStream

  3. FileStream

  4. InputStream

  5. DataInputStream

  1. What will happen when an attempt is made to compile and execute the following program? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
import java.io.*;
public class App {
  public static void main(String[] args) {
    File fd = new File("c:\\temp\\myfile.dat");
    FileOutputStream out = new FileOutputStream(fd);
    out.write(123);
    out.close();
  }
}
  1. The program will not compile

  2. The code will compile but a runtime exception will occur 

  3. The program will compile and execute to store the int value 123 in the disk file

  4. The program will compile and execute to store the byte value 123 in the disk file

  5. The program will compile and execute but nothing will be stored in the disk file

  1. If fd is a File object containing a path name, code a single statement to construct a DataInputStream object named istream for the file.

  1. True or False: If the following is the header of an instantiable class, an object of the class can be written to disk using a DataOutputStream.

public class someClass implements Serializable

  1. True

  2. False