Previous


1.1 Changes: ListOfNumbers Example

The ListOfNumbers example writes its output to a PrintStream. Creation of a PrintStream object has been deprecated in the JDK 1.1 to encourage programmers to use a new class, PrintWriter, instead of a PrintStream.

The PrintWriter class is very similar to the PrintStream class, and in the case of the ListOfNumbers example, a PrintWriter can be used in place of a PrintStream without other changes to the code. Here's a 1.1 version of the ListOfNumbers example:

import java.io.*;
import java.util.Vector;

class ListOfNumbers {
    private Vector victor;
    final int size = 10;

    public ListOfNumbers () {
        int i;
        victor = new Vector(size);
        for (i = 0; i < size; i++)
            victor.addElement(new Integer(i));
    }
    public void writeList() {
        PrintWriter pWriter = null;

        try {
            int i;

            System.out.println("Entering try statement");
            pWriter = new PrintWriter(
                  new BufferedOutputStream(
                     new FileOutputStream("OutFile.txt")));
        
            for (i = 0; i < size; i++)
                pWriter.println("Value at: " + i + " = " + victor.elementAt(i));
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());
        } finally {
            if (pWriter != null) {
                System.out.println("Closing PrintWriter");
                pWriter.close();
            } else {
                System.out.println("PrintWriter not open");
            }
        }
    }
}
See for information about this and other changes to the java.io package.


Previous