next up previous
Next: Generalized input and output Up: Unit 09 Previous: A program that (sometimes)

Interleaving reading and writing

In general, a program performs both input and output and these are interleaved. Output operations are internally handled via an output buffer, and to ensure that interleaved input and output function properly from the point of view of the user interacting with the program, we have to empty the output buffer before obtaining the next input. This can be done by using the flush() method associated to an OutputStream object.

import java.io.*;

public class Plural2 {
  public static void main(String[] args) throws IOException {
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader keyboard = new BufferedReader(isr);
    System.out.print("Insert a word: ");
    System.out.flush();
    String line = keyboard.readLine();
    System.out.println("The plural of " + line + " is " + line + "s.");
  }
}

Note: Depending on how the OutputStream was created, the flush() operation may be performed automatically by the methods that write on the stream.


next up previous
Next: Generalized input and output Up: Unit 09 Previous: A program that (sometimes)