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.
Also Read: How To Close Applications Or Windows On Mac
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.
Also Read: How To Close Apps On Apple TV
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.