InputStream and OutputStream Classes

The following is the UML class diagram for a few commonly used concrete subclasses of InputStream.  Note that the StreamTokenizer class shown in the diagram is NOT a subclass of InputStream.   StreamTokenizer is a utility class used to parse the stream of input. It is discussed in a latter section of this lab.  

The first step in using a concrete input stream class is to specify its source for its constructor.  For instance, if I want to read the contents of a file into a String, you may want to use the FileInputStream class and specify the name of the input file in the constructor for FileInputStream.  The following is a sample code.  Try it out.

    import java.io.*;
 

    ...
 

    String buffer = new String();

    // read bytes until eof
    try  {
        // FileInputStream constructor takes either a String, a File object, or a FileDescriptor object
        FileInputStream infile = new FileInputStream("myfile.txt");

        for(int i = infile.read(); i != -1; i = infile.read())  {
            buffer += (char) i;
        }

        infile.close();
    }
    catch(IOException e) {
        System.err.println("Could not read from myfile.txt");
    }
    catch(FileNotFoundException e) {
        System.err.println("myfile.txt not found");
    }
 

The InputStream's available() method returns the number of bytes that can be read from the stream, and the close() method closes the link between the program and the source of the data.  After you close the stream, you cannot read from it anymore until you open it up again.  The reset() method sends the "pointer" to the stream back to the top of the file.  Several read() methods exist that you can use.  All data comes out as ints or bytes--to convert to chars you will have to cast them.

Similar methods exist for OutputStream.  Below is a UML diagram for commonly used subclasses of OutputStream.