Java - FileOutputStream close() method



Description

The Java FileOutputStream close() method is used to release system resources and ensure that all written data is properly saved to the file. If a file output stream is not closed, data loss or resource leaks may occur.

Declaration

Following is the declaration for java.io.FileOutputStream.close() method −

public void close()

Parameters

NA

Return Value

The method does not return any value.

Exception

NA

Example - Usage of FileOutputStream close() method

The following example shows the usage of Java FileOutputStream close() method.

FileOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      FileOutputStream fos = null;
      
      try {
         // create new file output stream
         fos = new FileOutputStream("text.txt");
         
         // close stream
         fos.close();
         
         // try to write into underlying stream
         fos.write(65);
         fos.flush();
         fos.close();
   
      } catch(Exception ex) {
         // if any error occurs
         System.out.print("IOException: File output stream is closed");
      } finally {
         // releases all system resources from the streams
         if(fos!=null)
            fos.close();
      }
   }
}

Output

Assumption

Assuming we have a text file test.txt in current directory, which has the following content. This file will be used as an input for our example program.

ABCDEF

Let us compile and run the above program, this will produce the following result−

IOException: File output stream is closed

Example - Closing FileOutputStream After Writing

The following example shows the usage of Java FileOutputStream close() method. This example demonstrates how to manually close a FileOutputStream after writing data to a file.

FileOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
   public static void main(String[] args) {
      FileOutputStream fos = null;
      try {
         // Open a file output stream
         fos = new FileOutputStream("output.txt");

         // Write some data to the file
         String data = "Hello, World!";
         fos.write(data.getBytes());

         System.out.println("Data written successfully.");

      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         // Close the FileOutputStream in the finally block to ensure closure
         try {
            if (fos != null) {
               fos.close();
               System.out.println("FileOutputStream closed successfully.");
            }
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result−

Data written successfully.
FileOutputStream closed successfully.

Explanation

  • A FileOutputStream is created for "output.txt".

  • The string "Hello, World!" is converted into bytes and written to the file.

  • The close() method is called inside a finally block to ensure that the file is always closed, even if an exception occurs.

  • Checking if (fos != null) prevents a NullPointerException in case the file wasn't successfully opened.

Example - Using try-with-resources for Auto-Close

The following example shows the usage of Java FileOutputStream close() method. This example demonstrates the try-with-resources approach, where close() is automatically called.

FileOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
   public static void main(String[] args) {
      // Try-with-resources ensures automatic closing of the stream
      try (FileOutputStream fos = new FileOutputStream("output.txt")) {

         // Write data to the file
         String data = "Java FileOutputStream Example";
         fos.write(data.getBytes());

         System.out.println("Data written successfully.");

      } catch (IOException e) {
         e.printStackTrace();
      } 
      // No need for an explicit close() call; it happens automatically
   }
}

Output()

Let us compile and run the above program, this will produce the following result−

Data written successfully.

Explanation

  • A FileOutputStream is created for "output.txt" inside a try-with-resources block.

  • Data is written to the file using write().

  • No need to explicitly call close(). Java automatically closes the stream when the try block exits.

  • This approach is more concise and preferred in modern Java (introduced in Java 7).

java_io_fileoutputstream.htm
Advertisements