Abbey Workshop

Java -- Read a Line of Input from the Console

This small program shows how to read a line of text from the console or keyboard using Java. Click on the link below to see the code for this program.

   1:import java.io.*;
   2:
   3:/**
   4:    This class demonstrates how to read a line of text from the keyboard
   5:*/
   6:class ReadLine{
   7:    public static void main(String[] args) throws IOException{
   8:        String CurLine = ""; // Line read from standard in
   9:        
  10:        System.out.println("Enter a line of text (type 'quit' to exit): ");
  11:        InputStreamReader converter = new InputStreamReader(System.in);
  12:        BufferedReader in = new BufferedReader(converter);
  13:
  14:        
  15:        while (!(CurLine.equals("quit"))){
  16:            CurLine = in.readLine();
  17:            
  18:            if (!(CurLine.equals("quit"))){
  19:                System.out.println("You typed: " + CurLine);
  20:            }
  21:        }
  22:    }
  23:}

View the Source Code

Here is some sample output from the program.

java ReadLine
Enter a line of text (type 'quit' to exit):
Line 1
You typed: Line 1
Line 2
You typed: Line 2
quit

Notes

First, input from the keyboard or console is read from the System.in object which functions as standard input. This data is wrapped by an InputStreamReader which reads data one character at a time. To read this data a line at a time, a BufferedReader is wrapped around the InputStreamReader. Using the BufferedReader, a line at a time is read as shown on line 16. If the line is not equal to "quit" it is printed out.