Close a Scanner in Java

  1. Close a Scanner in Java After Printing the Standard Input From the User
  2. Close a Scanner in Java After Printing a Specified String That Has New Line Characters in Between
  3. Use the close() Method to Close Scanner in Java After Reading the Contents of a File

In this tutorial, we will learn how to close a scanner in Java, and when we should use it. The Scanner class has a method close() that is especially available to close the opened scanner. Even if we don’t call the close() method explicitly, the interface Closeable will be invoked, closing the stream. It is a good practice to close a scanner explicitly.

Below are the examples that show how and when we can use the Scanner.close() method.

Close a Scanner in Java After Printing the Standard Input From the User

In the code below, we have created a Scanner object in that takes the System.in standard input from the user in the constructor. The method nextLine() returns the input that was skipped. It reads the entire line of input till the end of the line, including spaces and line separators.

The input is printed, and then we close the Scanner by calling the close() method on the Scanner object in. After the Scanner is closed, if we want to use in like we are doing below with myString2, it will throw an exception because the stream or Scanner has been closed.

import java.util.Scanner; 

public class CloseScanner {
    public static void main (String [] args){
      
        Scanner in = new Scanner (System.in);
        System.out.print ("Enter a String: ");
      
        String mystring = in.nextLine();
        System.out.println("The String you entered is: " + mystring);
        in.close();
          
        String myString2 = in.nextLine();
        System.out.println(myString2);
          
    }
}

Output:

Enter a String: the cat is white
The String you entered is: the cat is white

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150)
	at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1781)
	at java.base/java.util.Scanner.nextLine(Scanner.java:1649)
	at com.company.Main.main(Main.java:20)

Close a Scanner in Java After Printing a Specified String That Has New Line Characters in Between

In this example, we will separate the string s into different lines using \n and nextLine(). \n is used to indicate a new line, and as the scanner.nextLine() notices a new line, it goes to a new line and then prints it. Thus the output has all the three subjects in s in different lines.

This is one of the situations when we might want to call the close() method as we don’t want the scanner to scan any further new lines.

import java.util.Scanner;

public class CloseScanner {
    public static void main (String [] args){
        try {
            String s = " English \n Maths \n Science ";
            Scanner scanner = new Scanner(s);
            System.out.println(scanner.nextLine());
            System.out.println(scanner.nextLine());
            System.out.println(scanner.nextLine());

            scanner.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}

Output:

 English 
 Maths 
 Science 

Use the close() Method to Close Scanner in Java After Reading the Contents of a File

It is recommended to always close the Scanner when we are reading a file. It ensures that no input or output stream is opened, which is not in use. The following example shows how we can read a string from the file and then close the scanner once the operation has been done.

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

public class CloseScanner {
    public static void main (String [] args){
      
        try {
            File file = new File("/Users/john/Documents/Example.txt");
            Scanner scanner = new Scanner(file);
            StringBuffer sb = new StringBuffer();
            while (scanner.hasNext()) {
                sb.append(" " + scanner.nextLine());
            }
            System.out.println(sb);
          	scanner.close();
        }
        catch(Exception e){
                System.out.println(e.getMessage());
        }
      
    }
}

Output:

Hello, You are in a text file.

Related Article - Java Scanner

  • Get a Char From the Input in Java
  • Related Article - Java Scanner

  • Get a Char From the Input in Java