Thursday 17 September 2015

Java: Read input from console

In this post, i am going to show, how to read input from onsole. Following are some of the ways to read input from console in Java.
a.   Using BufferedReader
b.   Using Scanner
c.    Using System.console
d.   Using DataInputStream

Using BufferedReader
First initialize BufferedReader object, next call ‘read*’ methods. 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
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));
  System.out.println("Enter input");
  String input = br.readLine();
  System.out.println("You entered " + input);
 }
}

Using Scanner
First initialize Scanner instance and call ‘next*’ methods to read data from console.

import java.io.IOException;
import java.util.Scanner;

public class Main {
 public static void main(String args[]) throws IOException {
  Scanner scanner = new Scanner(System.in);
  System.out.println("Enter input");
  String input = scanner.nextLine();
  System.out.println("You entered " + input);
  scanner.close();
 }
}


Using System.console

import java.io.IOException;

public class Main {
 public static void main(String args[]) throws IOException {
  System.out.println("Enter input");
  String input = System.console().readLine();
  System.out.println("You entered " + input);
 }
}


Using DataInputStream

import java.io.DataInputStream;
import java.io.IOException;

public class Main {
 public static void main(String args[]) throws IOException {
  DataInputStream dis = new DataInputStream(System.in);
  System.out.println("Enter input");
  String input = dis.readLine();
  System.out.println("You entered " + input);
 }
}

'readLine' method of DataInputStream class is deprecated, so it is better not to use in your application.



No comments:

Post a Comment