Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

Close Java Files Automatically with Try-with-Resources

Use Java try-with-resources to close files and streams automatically, with defined behavior for returns, exceptions, and multiple resources.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To close a file in Java without writing a manual finally block, declare its reader, writer, or stream in a try-with-resources statement. Java closes it when control leaves the statement—whether the body finishes, returns, or throws. This also defines what happens if both your code and cleanup fail.

How to close a file in Java without a finally block

Use a resource that implements AutoCloseable. Java’s Closeable interface extends AutoCloseable, so common file readers, writers, and streams can be used directly. Oracle’s Java Tutorial explains that the statement ensures each resource is closed at its end: The try-with-resources Statement.

try (BufferedReader reader = Files.newBufferedReader(path)) {
    return reader.readLine();
}

When the return is evaluated, Java closes reader before the method returns. It also closes the reader if readLine() throws. This handles cleanup, but it does not remove checked-exception requirements: the surrounding method must still catch or declare exceptions that its file operations can throw.

What happens when initialization or closing fails?

Resources are initialized from left to right and closed in reverse order. If initializing a later resource fails, Java closes any earlier resources that initialized successfully. A resource is closed only if it initialized to a non-null value, as specified in the Java Language Specification, Java SE 26 Edition, §14.20.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For example, the second resource below is closed before the first:

try (InputStream input = Files.newInputStream(source);
     OutputStream output = Files.newOutputStream(destination)) {
    input.transferTo(output);
}

This order can matter when one resource depends on another. Declare resources in the order they should be acquired, and let the reverse closing order release dependent resources first.

When both the body and close fail

If the body throws an exception and closing also throws, the body’s exception remains primary; the close exception is recorded as suppressed. Inspect suppressed exceptions with Throwable.getSuppressed() when diagnosing cleanup failures. If the body completes normally but closing fails, the close exception propagates instead.

How try-with-resources compares with manual finally cleanup

Concern Try-with-resources Manual try/finally
Cleanup after body returns or throws Closes initialized, non-null resources automatically. Requires explicit close logic in finally.
Body and close both throw Preserves the body exception and suppresses close exceptions. Cleanup logic must explicitly avoid replacing the body exception.
Multiple resources Declares them together; closes them in reverse initialization order. Requires nested handling or multiple close operations and careful ordering.
Existing variables Java 9 and later allow final or effectively final, definitely assigned variables in the resource specification. Can use existing variables, but cleanup remains manual.

Try-with-resources is therefore more than a shorter spelling of finally: the language specifies the cleanup sequence and exception behavior. Oracle’s Java SE 8 language guide describes the rules for resources and exception handling: Try-with-resources in the Java SE 8 language guide. These semantics do not establish a measured speed or productivity advantage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can you use an existing resource variable?

Yes, in Java 9 and later, a final or effectively final variable that is definitely assigned can appear directly in the resource specification:

BufferedReader reader = Files.newBufferedReader(path);
try (reader) {
    return reader.readLine();
}

The variable must not be reassigned. This syntax is useful when the resource has already been created; declaring it inside the parentheses, as in the first example, remains clear and works in older Java versions that support try-with-resources.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When finally is still useful

Try-with-resources replaces manual close() calls for objects implementing AutoCloseable; it does not make finally obsolete. You may put a catch or finally after the try-with-resources statement. Those clauses run after the declared resources have been closed. Use finally for cleanup that is not represented by an AutoCloseable resource, while keeping resource closure in the resource statement.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.