Scanner Class in Java

Filed Under: Java

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

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.

JavaFileScanner.java


package com.journaldev.files;

import java.io.IOException;
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 journaldev.com
         *  Phone : 1234567890
         */
        String fileName = "/Users/pankaj/source.txt";
        Path path = Paths.get(fileName);
        Scanner scanner = new Scanner(path);
        
        //read file line by line
        scanner.useDelimiter(System.getProperty("line.separator"));
        while(scanner.hasNext()){
            System.out.println("Lines: "+scanner.next());
        }
        scanner.close();
        //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"));
        scanner.useDelimiter(System.getProperty("line.separator"));
        while(scanner.hasNext()){
            //parse line to get Emp Object
            Employee emp = parseCSVLine(scanner.next());
            System.out.println(emp.toString());
        }
        scanner.close();
        
        //read from system input
        System.out.println("Read from system input:");
        scanner = new Scanner(System.in);
        System.out.println("Input first word: "+scanner.next());
    }
    
    private static Employee parseCSVLine(String line) {
         Scanner scanner = new Scanner(line);
         scanner.useDelimiter("\\s*,\\s*");
         String name = scanner.next();
         int age = scanner.nextInt();
         String gender = scanner.next();
         JavaFileScanner jfs = new JavaFileScanner();
         return jfs.new Employee(name, age, gender);
    }

    public class Employee{
        private String name;
        private int age;
        private String gender;
        
        public Employee(String n, int a, String gen){
            this.name = n;
            this.age = a;
            this.gender = gen;
        }
        
        @Override
        public String toString(){
            return "Name="+this.name+"::Age="+this.age+"::Gender="+this.gender;
        }
    }

}

Output of the above program is:


Lines: My Name is Pankaj
Lines: My website is journaldev.com
Lines: Phone : 1234567890
Name=Pankaj::Age=28::Gender=Male
Name=Lisa::Age=30::Gender=Female
Name=Mike::Age=25::Gender=Male
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

Comments

  1. kiran says:

    Useful tutorial even after four years.

  2. mathi says:

    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

  3. Manohar says:

    Nice article.

  4. mark says:

    Where is the Path class?

    1. Pankaj says:

      Path class is added in Java-7. I think you are using older version.

      http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html

  5. Pravindrasingh says:

    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?

  6. karan patel says:

    how to use scanner class with servlet??
    it will work????

  7. shaun says:

    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

  8. shaun says:

    i could not understand what is java File Scanner in line 54,i know Scanner but JavaFile Scanner

    1. Pankaj says:

      JavaFileScanner is the class name of the program you are looking. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages