(back to the documentation page)
There are several ways to create Readers:
For a file:
FileReader reader = new FileReader("filename");For the terminal:
InputStreamReader reader = new InputStreamReader(System.in);For a url:
URL url = new URL("http://www.cs.williams.edu/~index.html");
InputStreamReader reader = new InputStreamReader(url.openStream());For a Socket:
InputStreamReader reader = new InputStreamReader(socket.getInputStream());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.
To close a reader, call the close() method:
reader.close();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 a file:
PrintWriter writer = new PrintWriter(new FileWriter("filename"));For the terminal: System.out is already a PrintWriter.
For a Socket:
PrintWriter writer = new PrintWriter(
  new OutputStreamWriter(
    socket.getOutputStream()
  ),
  true
);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.
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.
Close writers just like readers:
writer.close();