Close Your Scanner With the close() Method

To close a Scanner in Java, call the close() method on your Scanner object. This tells Java to release the resources the Scanner is using — typically the input stream it was reading from. Once you call close(), you cannot use that Scanner again.

The simplest way is a single line after you finish reading:

scanner.close();

If your Scanner is reading from a file or network connection, closing it also closes that underlying resource. If it is reading from System.in (the keyboard), closing it will close standard input for your entire program, which is usually not what you want.

Key Takeaways

  • Call scanner.close() when you are finished reading to free up system resources and avoid memory leaks.
  • Closing a Scanner that reads from a file also closes that file, so make sure you have finished reading before you close.
  • Do not close a Scanner reading from System.in unless you want to shut down keyboard input for your whole program.
  • Use try-with-resources (try with parentheses) to close your Scanner automatically, even if an error occurs.
  • If close() throws an exception, wrap it in a try-catch block or declare throws IOException in your method signature.

Why You Need to Close a Scanner

Every Scanner holds onto a system resource — a file handle, a network socket, or an input stream. If you create many Scanners without closing them, your program will eventually run out of file handles and crash. This is called a resource leak.

Closing the Scanner tells the operating system that your program is done with that resource and it can be reused. In small programs this may not matter, but in long-running applications or loops that create many Scanners, it becomes critical.

Java does not automatically close Scanners the way it does with some other objects. You must close them yourself, or use a language feature that does it for you.

The Try-With-Resources Pattern (Recommended)

The safest way to use a Scanner is the try-with-resources statement. Java automatically closes the Scanner when the block ends, even if an error happens:

try (Scanner scanner = new Scanner(new File("data.txt"))) {   while (scanner.hasNextLine()) {     String line = scanner.nextLine();     System.out.println(line);   } }

The Scanner is declared inside the parentheses after try. When the closing brace is reached, Java calls close() automatically. If an exception is thrown inside the block, the Scanner is still closed before the exception propagates.

This pattern works with any object that implements AutoCloseable, which Scanner does. It is the modern standard in Java and removes the risk of forgetting to close.

Closing a Scanner in a Try-Catch Block

If you cannot use try-with-resources, put close() in a finally block so it runs whether or not an error occurs:

Scanner scanner = new Scanner(new File("data.txt")); try {   while (scanner.hasNextLine()) {     String line = scanner.nextLine();     System.out.println(line);   } } finally {   scanner.close(); }

The finally block runs after the try block completes, or if an exception is thrown. This guarantees the Scanner is closed even if nextLine() or another method throws an exception.

The close() method itself can throw an IOException if something goes wrong closing the underlying resource. If you need to handle that, wrap it in another try-catch:

finally {   try {     scanner.close();   } catch (IOException e) {     e.printStackTrace();   } }

What Happens When You Do Not Close

If you forget to close a Scanner, the resource stays open until the program ends or the garbage collector eventually cleans it up. In a short script this may cause no visible problem. In a loop that creates hundreds of Scanners, or in a server that runs for days, you will eventually hit the system limit on open files.

When that happens, you get an exception like "Too many open files" and your program crashes. The error is hard to debug because it does not happen at the line where you create the Scanner — it happens later, when the system runs out of resources.

Closing Scanners as soon as you finish with them prevents this entirely. It is a small habit that saves hours of troubleshooting.

Closing a Scanner That Reads From System.in

If your Scanner reads from the keyboard (System.in), closing it will close standard input for your entire program. After that, no code can read from the keyboard anymore, even if you create a new Scanner.

Scanner keyboard = new Scanner(System.in); String input = keyboard.nextLine(); keyboard.close(); // This closes System.in for the whole program

For this reason, many programs do not close a Scanner reading from System.in. If you are writing a small utility, it is usually fine to leave it open — the program will close it when it exits anyway.

If you must close it, or if you need to read from the keyboard again later, consider wrapping System.in in a BufferedReader instead, or creating only one Scanner for the entire program and reusing it.

Common Mistakes When Closing

A frequent mistake is closing the Scanner before you finish reading from it. If you call close() and then try to call hasNextLine() or nextLine(), you will get a "Scanner closed" exception:

Scanner scanner = new Scanner(new File("data.txt")); scanner.close(); scanner.nextLine(); // Exception: Scanner closed

Make sure all your reading is complete before you close. If you are using try-with-resources, this is automatic — the block ends when you are done reading.

Another mistake is closing the underlying stream instead of the Scanner. If you pass a FileInputStream to the Scanner and then close the stream, the Scanner becomes unusable:

FileInputStream fis = new FileInputStream("data.txt"); Scanner scanner = new Scanner(fis); fis.close(); // Wrong — closes the stream, not the Scanner scanner.nextLine(); // May fail

Always close the Scanner, not the stream it wraps. The Scanner will close the stream for you.

Frequently Asked Questions

Do I have to close a Scanner if it reads from a String?

Technically no — a Scanner reading from a String does not hold a file handle or network resource. However, it is still good practice to close it, because your code may change later to read from a file instead. Using try-with-resources costs nothing and makes your code safer.

What if close() throws an exception?

Wrap it in a try-catch block, or declare throws IOException in your method signature. In most cases you can safely ignore the exception — it usually means the resource was already closed or the system is shutting down. Printing the stack trace with e.printStackTrace() is enough for debugging.

Can I close a Scanner twice?

Yes, calling close() twice is safe. The second call does nothing. This is why try-with-resources is safe — if close() is called twice, the second call is harmless.

Does closing the Scanner close the file?

Yes. When you close a Scanner that reads from a file, Java closes the file handle. The file itself is not deleted — it is just closed so other programs can use it.

What is the difference between close() and flush()?

flush() writes any buffered data to the underlying stream but does not close it. close() flushes the data and then closes the resource. For a Scanner (which reads, not writes), flush() has no effect. Always use close() when you are done.