Thursday, November 24, 2011

How to read input from console in Java


How to read input from console -Java

There are two common ways to read input from console.

1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5

First we look up on InputStreamReader , BufferedReader example

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

public class ReadConsoleSystemInput {
  public static void main(String[] args) {

System.out.println("Enter something here to Read : ");

try{
   BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
   String s = bufferRead.readLine();

   System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}

  }
}

Another way is using Scanner class


import java.util.Scanner;

public class ReadConsoleScannerInput {
  public static void main(String[] args) {

 System.out.println("Enter something here to Read : ");

  String s;

       Scanner In = new Scanner(System.in);
       s = In.nextLine();

       In.close();          
       System.out.println(s);
  }
}

1 comment:

  1. Hey
    I appreciate you writing on such a subject, I really needed to find this info. Cheers for discussing!
    With Best Wishes
    bedroom | sofa | kitchen | bathroom | living room

    ReplyDelete