Java - Use System.in object with a BufferedReader

Introduction

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.

Demo

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    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();/*from ww  w . j  a  v a  2  s  .  c  o  m*/
      if (text.equalsIgnoreCase("q")) {
        System.out.println("You have decided to exit the program");
        break;
      } else {
        System.out.println("You typed: " + text);
      }
    }
  }
}

Result

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 System.in.read() will read from stdin.txt file

Related Topic