How to Close a File in Java

Rupam Yadav Feb 02, 2024
  1. Close a File Using the try-with-resources in Java (7+)
  2. Use the close() Method to Close a File in Java
  3. Conclusion
How to Close a File in Java

Handling files is a fundamental task in Java programming, and proper resource management is essential. In the past, closing files required manual intervention using finally blocks or the close() method, which could be error-prone and lead to resource leaks.

However, with the introduction of try-with-resources in Java 7 and the continued use of the close() method, managing files has become more efficient and less error-prone.

In this article, we will explore how to effectively close files in Java using both try-with-resources and the close() method. We’ll discuss the syntax, provide practical examples for each method, and highlight the importance of resource management when working with files.

Close a File Using the try-with-resources in Java (7+)

Prior to Java 7, developers had to manually close files using finally blocks, which could be error-prone and lead to resource leaks. However, with the introduction of try-with-resources in Java 7, handling files became more efficient and less error-prone.

try-with-resources is a language feature introduced in Java 7 that simplifies resource management. It automatically manages the closing of resources, such as files, at the end of the try block, whether the block is exited normally or due to an exception. The syntax for using try-with-resources with files is straightforward:

try (ResourceType resource = new ResourceType()) {
  // Use the resource here
} catch (Exception e) {
  // Handle exceptions if necessary
// Resource is automatically closed when exiting this block

Here’s how to use try-with-resources to close files:

  1. Resource Initialization: In the parentheses following the try keyword, you declare and initialize the resource (in this case, a file-related class, such as FileInputStream, FileOutputStream, BufferedReader, or BufferedWriter). The resource should implement the AutoCloseable interface or its subinterfaces, such as Closeable.
  2. Resource Usage: Inside the try block, you use the resource as needed for reading, writing, or other operations. You don’t need to explicitly close the resource in your code.
  3. Resource Closure: Once the execution leaves the try block, whether it’s due to normal completion or an exception, the resource is automatically closed. You don’t need to write a finally block to ensure closure.

Practical Example

Let’s see how try-with-resources works with a practical example of reading data from a file:


public class FileReadExample {
  public static void main(String[] args) {
    try (FileInputStream fis = new FileInputStream("example.txt")) {
      int data;
      while ((data = != -1) {
        System.out.print((char) data);
    } catch (IOException e) {
    // The FileInputStream is automatically closed

In this example, we open a file using FileInputStream within the try block and read its contents. Once the block is exited, whether due to normal completion or an exception, the FileInputStream is automatically closed, releasing system resources.

Exception Handling

try-with-resources simplifies exception handling as well. If an exception occurs within the try block, the resource is closed automatically before the exception is propagated up the call stack. You can catch and handle exceptions in the catch block as needed.


public class FileWriteExample {
  public static void main(String[] args) {
    try (FileOutputStream fos = new FileOutputStream("output.txt")) {
      // Write data to the file
      fos.write("Hello, World!".getBytes());
    } catch (IOException e) {
    // The FileOutputStream is automatically closed

Use the close() Method to Close a File in Java

The BufferedWriter class is utilized in the following program. This class allows you to efficiently write arrays, strings, and characters into a character-output stream.

We also employ the FileWriter class, designed for writing streams of characters, and the BufferedWriter class.

A file path is represented by an instance of the File class file. An abstract pathname is constructed from the specified pathname string.

The BufferedWriter’s write() method saves some text to the file. The newLine() method adds a /n as a line separator.

The majority of streams don’t need to be closed after being used. When the source is an Input/Output Channel, it is recommended to close the stream.

We should invoke the close() method before terminating the program or executing any file operations. We might lose some data if we don’t.

As a result, to close the stream and keep the data secure, the close() method is utilized.

Streams include a method called BaseStream.close(), which implements Autoclosable. Almost all stream instances don’t need to be closed because they’re supported by collections, which are arrays that don’t need any additional resource management.

The stream should be closed if the source is an IO channel.

The contents of the file are shown below before conducting the write operation.


public class CloseFile {
  public static void main(String[] args) throws Exception {
    File file = new File("/Users/John/Temp/demo1.txt");
    if (file.exists()) {
      BufferedWriter bufferWriter = new BufferedWriter(new FileWriter(file, true));
      bufferWriter.write("New Text");

File Contents Before Write Operation

After performing the write operation, the file’s contents changed.

Perform Write Operation


In this article, we’ve demonstrated how to use both try-with-resources and the close() method to close files, both for reading and writing operations, and how each approach simplifies exception handling.

These methods are considered best practices in modern Java programming for closing files and other resources, ensuring efficient and reliable resource management.

Author: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.


Related Article - Java File