Java Scanner class is part of the java.util package. It was introduced in Java 1.5 release. The Scanner is mostly used to receive user input and parse them into primitive data types such as int, double or default String. It’s a utility class to parse data using regular expressions by generating tokens.
If you look at the Scanner class, there are many constructors.
Most of the constructors are using one of the three objects:
If you look at the second argument, it’s to specify a character set if you don’t want to use the default character set for parsing.
Let’s look at some of the most commonly used Scanner class methods.
There are many utility methods to check and directly parse the input token in int, short, long, byte, BigDecimal, etc.
Let’s look at some of the common usages of the Scanner class with sample code snippets.
This is the most common use of the Scanner class. We can instantiate with System.in as input source and read the user input.
// read user input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
String name = sc.next();
System.out.println("Hello " + name);
sc.close();
Output:
Please enter your name
Pankaj
Hello Pankaj
Well, it looks easy and working fine. But, the above code has an issue. Without reading the next section, can you check the code and try to identify it?
Let’s see what happens when I write my full name in the input.
Please enter your name
Pankaj Kumar
Hello Pankaj
Now you must have got it, it’s happening because whitespace is the delimiter. The scanner is breaking the input into two tokens - Pankaj and Kumar. But, we are calling the next() method just once, so only “Hello Pankaj” is printed.
How do we fix this?
It’s simple. We can change the delimiter to a newline character using the useDelimiter() method.
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
System.out.println("Please enter your name");
String name = sc.next();
System.out.println("Hello " + name);
sc.close();
Let’s look at a simple example to read and parse CSV files using the scanner class. Let’s say, I have an employees.csv file with the following content.
1,Jane Doe,CEO
2,Mary Ann,CTO
3,John Lee,CFO
Let’s read the file and get a list of Employees in our Java program.
package com.journaldev.java;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ScannerExamples {
public static void main(String[] args) throws IOException {
// create scanner for the CSV file
Scanner sc = new Scanner(new File("employees.csv"));
// set delimiter as new line to read one line as a single token
sc.useDelimiter(System.getProperty("line.separator"));
// create the List of Employees
List<Employee> emps = new ArrayList<>();
while (sc.hasNext()) {
Employee emp = parseEmployeeData(sc.next());
emps.add(emp);
}
// close the scanner
sc.close();
// print employee records
System.out.println(emps);
}
private static Employee parseEmployeeData(String record) {
// create scanner for the String record
Scanner sc = new Scanner(record);
// set delimiter as comma
sc.useDelimiter(",");
Employee emp = new Employee();
emp.setId(sc.nextInt());
emp.setName(sc.next());
emp.setRole(sc.next());
// close the scanner
sc.close();
return emp;
}
}
class Employee {
private int id;
private String name;
private String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "Emp[" + id + "," + name + "," + role + "]";
}
}
Output: [Emp[1,Jane Doe,CEO], Emp[2,Mary Ann,CTO], Emp[3,John Lee,CFO]]
Let’s say we have a string source and we want to process only integers present in that. We can use the scanner with the non-digit regex to get only integers as tokens to process them.
//using regex to read only integers from a string source
String data = "1a2b345c67d8,9#10";
Scanner sc1 = new Scanner(data);
// setting non-digit regex as delimiter
sc1.useDelimiter("\\D");
while(sc1.hasNext()) {
System.out.println(sc1.next());
}
// don't forget to close the scanner
sc1.close();
Output:
1
2
345
67
8
9
10
Java Scanner is a utility class to read user input or process simple regex-based parsing of file or string source. But, for real-world applications, it’s better to use CSV parsers to parse CSV data rather than using the Scanner class for better performance.
Reference: API Doc, Regex in Java
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Useful tutorial even after four years.
- kiran
i need a simple program that it should take text as input using parser and analyse the text as output then it should perform AST using the output of parser
- mathi
Nice article.
- Manohar
Where is the Path class?
- mark
I want to read a method of java class line by line and do the analysis of each statement. Any idea how i can achieve it?
- Pravindrasingh
how to use scanner class with servlet?? it will work???
- karan patel
sir iam writing a program to extract email headers like From,to,Subject etc,how do i write it so that i can extract only lines followed by From: , To: and not the remaining text i tried Pattern.compile with scanner but not working
- shaun
i could not understand what is java File Scanner in line 54,i know Scanner but JavaFile Scanner
- shaun