Streams Cheat Sheet

(back to the documentation page)

Readers

Creating readers for different streams

There are several ways to create Readers:

Reading from streams

All readers allow you to read one character at a time with the read() method.

int ch = reader.read();

The variable ch is set to a character value between 0 and 255, or -1 when there are no more characters left in the stream (i.e., at the end of a file).

To read whole lines at a time, use a BufferedReader:

BufferedReader buffer = new BufferedReader(reader);

The reader variable is any reader made above. The following example shows how to read all lines in a file using a buffered reader:

String s;
BufferedReader buffer = new BufferedReader(new FileReader("filename"));
s = buffer.readLine();
while (s != null) {
    System.out.println(s);
    s = buffer.readLine();
}

The method readLine() returns null when the reader reaches the end of the stream.

Closing readers

To close a reader, call the close() method:

reader.close();

Writers

Creating writers for different streams

There are several ways to create Writers. We always want to create a PrintWriter for our writer so that we can write more than one character at a time:

For sockets, we need to use one extra parameter for the PrintWriter constructor to indicate that Java should treat the PrintWriter as something that writes to a network.

Writing to streams

You use a PrintWriter just as we have been using System.out all semester:

writer.println("some text");
writer.print("some text");

Unlike println, the print method does not start a new line after printing the text.

Closing writers

Close writers just like readers:

writer.close();