Skip to content
UoL CS Notes

Streams

COMP122 Lectures

Streams are an endless flow of data from a source to a destination:

graph LR
Source -->|write| 010010
010010 -->|read| Destination

Streams are objects. There are different classes for various types of sources and destinations.

Streams as Object

The standard library java.io implements streams in an object-oriented way.

The InputStream class is read from:

graph LR
subgraph InputStream
Source -->|write| 010010
end
010010 -->|read| Destination

The OutputStream class is written to:

graph LR
Source -->|write| 010010
subgraph OutputStream
010010 -->|read| Destination
end

Stream Contents

There are several basic types of data that can be transported by a stream:

  • Basic Input/OutputStreams are byte-based:
    • You can read/write a byte = 8 bits.
    • For example, public int InputStream.read() reads the next bytes of datat from the input stream.
  • java.io.Reader/Writer are based on characters:
    • char, or Character, store UTF-16 encoded characters.
    • public int Reader.read() reads the next character.

      This reads an int as the primitive type char is syntactic sugar for a 16-bit integer. This means that you need to cast the return type into a (char).

  • ObjectInputStream and ObjectOutputStream represent streams that can send whole objects.
    • Works as long as the object belongs to a class that implements the Serialisable interface.
    • public Object ObjectInputStream.readObject() reads the next object.

Standard Streams

The standard streams include:

  • stdin
  • stdout
  • stderr

These are represented in the following classes:

classDiagram
InputStream <|-- in
OutputStream <|.. PrintStream
PrintStream <|-- out
PrintStream <|-- err
class InputStream {
    +read() in
    +read(byte[] b) int
}
class OutputStream {
    +write(int b) void
    +write(byte[] b) void
}
class PrintStream {
    +print(boolean s) void
    +print(char c) void
    +print(char[] s) void
    +print(String s) void
    +println(String s) void
}

in, out and err in this diagram are representing the objects:

  • System.in
  • System.out
  • System.err

Java I/O Summary

  • All of Java’s input/output is based on Streams
  • InputStream, OutputStream:
    • Based on bytes.
  • Reader, Writer:
    • Based on characters.
  • There are many derived types in java.io:
    • File Access
    • Network Access