Scanner Class in Java With Examples

Scanner class in Java (java.util.Scanner) was introduced in Java 1.5 as a simple text scanner which can parse primitive types and strings using regular expressions.

Scanner Class in Java

Java Scanner class can be used to break the input into tokens with any regular expression delimiter and it’s good for parsing files also.

Scanner class can be used to read file data into primitive. It also extends String split() method to return tokens as String, int, long, Integer and other wrapper classes.

Java Scanner Example

Here I am using Scanner to read a file line by line, parsing a CSV file to create java object easily and read from the user input.

package com.journaldev.files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class JavaFileScanner {
    public static void main(String[] args) throws IOException {
         *  My Name is Pankaj
         *  My website is
         *  Phone : 1234567890
        String fileName = "/Users/pankaj/source.txt";
        Path path = Paths.get(fileName);
        Scanner scanner = new Scanner(path);
        //read file line by line
            System.out.println("Lines: ";
        //read CSV Files and parse it to object array
         * Pankaj,28,Male
         * Lisa,30,Female
         * Mike,25,Male
        scanner = new Scanner(Paths.get("/Users/pankaj/data.csv"));
            //parse line to get Emp Object
            Employee emp = parseCSVLine(;
        //read from system input
        System.out.println("Read from system input:");
        scanner = new Scanner(;
        System.out.println("Input first word: ";
    private static Employee parseCSVLine(String line) {
         Scanner scanner = new Scanner(line);
         String name =;
         int age = scanner.nextInt();
         String gender =;
         JavaFileScanner jfs = new JavaFileScanner();
         return Employee(name, age, gender);
    public class Employee{
        private String name;
        private int age;
        private String gender;
        public Employee(String n, int a, String gen){
   = n;
            this.age = a;
            this.gender = gen;
        public String toString(){
            return "Name=""::Age="+this.age+"::Gender="+this.gender;

Output of the above program is:

Lines: My Name is Pankaj
Lines: My website is
Lines: Phone : 1234567890
Read from system input:
Pankaj Kumar
Input first word: Pankaj

We can use java Scanner class to parse the input into specific datatype tokens.

Read this post to learn how to read CSV File using Scanner.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: