Here this example will tell us how to get a User input with InputStreamReader + BufferedReader.
Source Code
1)
package com.beginner.examples;
import java.util.Scanner;
public class GetUserInput {
public static void main(String[] args) {
//Using this format in Java8 automatically closes resources
try(Scanner scanner = new Scanner(System.in))
{
System.out.println("Enter your name:");
//Read user input
String name = scanner.nextLine();
System.out.println("Your name is:"+name);
}
}
}
Output:
Enter your name:
Tom
Your name is:Tom
2)
package com.beginner.examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GetUserInput_2 {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter your name:");
String line = reader.readLine();
System.out.println("Your name is :" + line);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Enter your name:
Jerry
Your name is :Jerry
References
Imported packages in Java documentation: