Java Scanner Class Example Tutorial

In this tutorial, we'll learn:
  1. Scanner class overview
  2. How does a Scanner work?
  3. How to use the Java Scanner class to read input
  4. How to read the file line by line with an example
  5. Convert InputStream to String

Video Tutorial

1. Scanner class overview

Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. With the help of Scanner in Java, we can get input from the user in primitive types as well as strings such as int, long, double, byte, float, short, strings, etc.

The below class diagram shows all the APIs/methods of Scanner class:

2. How does a Scanner work?

Basically, a Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace (blanks, tabs, and line terminators). The parsed tokens can be converted into primitive types and Strings using various next methods. 
Here’s the simplest example of using a Scanner to read String from the user:
System.out.println("Enter string input: ");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();

How to use the Java Scanner class to read input

Here is the complete Java program to read primitive types and strings from User's input:
package net.javaguides.examples;

import java.util.Scanner;

/**
 * Scanner class examples
 * @author Ramesh Fadatare
 *
 */
public class ScannerExamples {
    public static void main(String[] args) {

        // Create Scanner object
        Scanner scanner = new Scanner(System.in);

        // read user input as string
        System.out.println("Enter string input: ");
        scanner.nextLine();

        // read user input as integer
        System.out.println("Enter integer input");
        scanner.nextInt();

        // read user input as long
        System.out.println("Enter long input");
        scanner.nextLong();

        // read user input as float
        System.out.println("Enter float input");
        scanner.nextFloat();

        // read user input as byte
        System.out.println("Enter byte input");
        scanner.nextByte();

        // read user input as short
        System.out.println("Enter short input");
        scanner.nextShort();

        // read user input as boolean
        System.out.println("Enter boolean input");
        scanner.nextBoolean();

        // read user input as BigDecimal
        System.out.println("Enter BigDecimal input");
        scanner.nextBigDecimal();

        // read user input as BigInteger
        System.out.println("Enter BigInteger input");
        scanner.nextBigInteger();

        scanner.close();
    }
}
Output:
Enter string input: 
Ramesh
Enter integer input
100
Enter long input
120
Enter float input
12
Enter byte input
12
Enter short input
1
Enter boolean input
true
Enter BigDecimal input
120.01
Enter BigInteger input
12346

4. How to read the file line by line with an example

The following Java program uses the nextLine() method to read a text file line by line, and add all lines to a list of Strings:
package net.javaguides.examples;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Scanner class file read example
 * @author Ramesh Fadatare
 *
 */
public class ScannerFileReadExample {
    public static void main(String[] args) throws FileNotFoundException {
        String fileName = "sample.txt";

        try (Scanner scanner = new Scanner(new File(fileName))) {

            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        }
    }
}
Create a file named "sample.txt" and add a few lines to it and run the above program to read a text file line by line using Scanner class.

5. Convert InputStream to String

Here is a java program to convert an InputStream into a String using a Scanner:
package net.javaguides.examples;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerConvertInputStreamToString {
    public static void main(String[] args) throws FileNotFoundException {

        FileInputStream inputStream
            = new FileInputStream("sample.txt");

        Scanner scanner = new Scanner(inputStream);
        scanner.useDelimiter("A");

        String result = scanner.next();
        System.out.println(result);
        scanner.close();
    }
}
Output:
Hello
Java Guides

References

Comments