Scanner Class
The Scanner class is a simple text scanner which can
parse primitive types and strings using regular expressions. It is commonly used
for reading input from the console or parsing files.
Reading from Console
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello " + name);
Reading from File
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
System.out.println(data);
}
scanner.close();
Full Example
Output
Click Run to execute your code
Enjoying these tutorials?