Java - Use object with a BufferedReader


Create a BufferedReader object and read data from the keyboard one line at a time as string.

The following code keeps prompting the user to enter some text until the user enters Q or q to quit the program.



public class Main {
  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(;

    String text = "q";
    while (true) {
      // Prompt user to type some text
      System.out.print("Please type a message (Q/q to quit) "
          + "and press enter: ");

      // Read the text
      text = br.readLine();/*w w  w  . java2 s .c  o m*/
      if (text.equalsIgnoreCase("q")) {
        System.out.println("You have decided to exit the program");
      } else {
        System.out.println("You typed: " + text);


Divert standard input to come from a file, create an input stream object to represent that file and set that object using the System.setIn() method

FileInputStream fis = new FileInputStream("stdin.txt");
System.setIn(fis); // Now will read from stdin.txt file

Related Topic