Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Java Lesson 45: Low-level and high-level stream classes

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 45 by Jon Huhtala

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

  • Is part of the java.io package

  • Is an extension of the OutputStream class, an abstract class that describes the behavior of an output stream

Object

OutputStream

FileOutputStream
  • Is a low-level class that can be used to send individual, 8-bit bytes to a stream

  • Has several constructors. The most frequently used constructs a FileOutputStream object from a File object that encapsulates the file's pathname. For example, if fd is the reference of a File object

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.
  • Has a few useful methods. The two most used are:

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.

  • Example. The following program can be used to create a file of numbers on disk.

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

  • Is part of the java.io package

  • Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream

Object

InputStream

FileInputStream
  • Is a low-level class that can be used to read individual, 8-bit bytes from a stream

  • Has several constructors. The most frequently used constructs a FileInputStream object from a File object that encapsulates the file's pathname. For example, if fd is the reference of a File object

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.
  • Has a few useful methods. The most used are:

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.

  • Example. The following program can be used to read byte values from a disk file. It can be used to display the values stored by the previous sample program.

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

  • Is part of the java.io package

  • Is an extension of the FilterOutputStream class (a superclass that facilitates the chaining of high-level and low-level output streams)

Object

OutputStream

FilterOutputStream

DataOutputStream
  • Is a high-level class that can be used to send primitive values and UTF ("Unicode Transformation Format") strings to a stream

  • Has a single constructor that "chains" to an object that descends from the OutputStream class (such as a FileOutputStream object). For example, if fd is the reference of a File object

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.
  • Has many useful methods as follows:

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.

  • Example. The following program can be used to create a file of double values on disk.

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

  • Is part of the java.io package

  • Is an extension of the FilterInputStream class (a superclass that facilitates the chaining of high-level and low-level input streams)

Object

InputStream

FilterInputStream

DataInputStream
  • Is a high-level class that can be used to read primitive values and UTF ("Unicode Transformation Format") strings from a stream

  • Has a single constructor that "chains" to an object that descends from the InputStream class (such as a FileInputStream object). For example, if fd is the reference of a File object

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.
  • Has many useful methods as follows:

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.

  • Example. The following program can be used to read a file of double values from disk. It can be used to display the values stored by the previous sample program.

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("");
}

// 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

  • Is part of the java.io package

  • Is an extension of the OutputStream class, an abstract class that describes the behavior of an output stream

Object

OutputStream

ObjectOutputStream

  • Is a high-level class that can be used to send primitive values and "serializable" objects to a stream. All that is needed for an object to be serializable, is that its class must implement the Serializable interface. For example, if a Customer class is to be serializable, its header may be coded

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!

  • Has overloaded constructors but the most useful "chains" to an object that descends from the OutputStream class (such as a FileOutputStream object). For example, if fd is the reference of a File object

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.
  • Has many useful methods as follows:

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.

  • Example. The following program can be used to create a file of multiple array objects on disk.

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

  • Is part of the java.io package

  • Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream

Object

InputStream

ObjectInputStream

  • Is a high-level class that can be used to read primitive values and serializable objects from a stream

  • Has overloaded constructors but the most useful "chains" to an object that descends from the InputStream class (such as a FileInputStream object). For example, if fd is the reference of a File object

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.
  • Has many useful methods as follows:

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.

  • Example. The following program can be used to read a file of array objects from disk. It can be used to display the array values stored by the previous sample program.

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.

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

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:tempmyfile.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


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy