Java - ByteArrayOutputStream close() method



Description

The Java ByteArrayOutputStream close() method is used to release resources associated with the stream. However, unlike streams that rely on external resources (e.g., files or network connections), calling close() on a ByteArrayOutputStream has no real effect because it operates entirely on memory. You can continue using the stream even after closing it.

Despite this, calling

close()

is good practice to ensure consistency when managing streams.

Declaration

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

public void close()

Parameters

NA

Return Value

This method doesn't return any value.

Exception

NA

Example - Using ByteArrayOutputStream close() method

The following example shows the usage of Java ByteArrayOutputStream close() method. We've created a variable buf as byte[] and initialized with few bytes. We've created a ByteArrayOutputStream reference and then created a new ByteArrayOutputStream() object. We've used the close() method to close the stream before invoking write() method. Then we're writing the byte array to ByteArrayOutputStream object using its write() method and printing its string version.

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      byte[] buf = {65, 66, 67, 68, 69};
      ByteArrayOutputStream baos = null;
      
      try {
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();
         
         // close is invoked before baos.
         baos.close();
         
         // writing byte array to the output stream
         baos.write(buf);
         
         // print as string
         System.out.print(baos.toString());
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(baos!=null)
            baos.close();
      }   
   }
}

Output

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

ABCDE

Example - Closing ByteArrayOutputStream After Writing Data

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

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) {
      // Create a ByteArrayOutputStream
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

      try {
         // Write some data to the output stream
         outputStream.write("Hello, World!".getBytes());

         // Convert the stream to a string and print it
         System.out.println("Data written to stream: " + outputStream.toString());

         // Close the output stream
         outputStream.close();
         System.out.println("ByteArrayOutputStream closed.");
      } catch (IOException e) {
         System.err.println("IOException occurred: " + e.getMessage());
      }
   }
}

Output

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

Data written to stream: Hello, World!
ByteArrayOutputStream closed.

Explanation

  • A ByteArrayOutputStream is created.

  • Data is written to the stream using the write(byte[]) method.

  • The content of the stream is printed by converting it to a string using toString().

  • The close() method is called to formally close the stream, although this has no effect for ByteArrayOutputStream.

  • Closing the stream ensures that the code follows a consistent practice of closing resources.

Example - Using close() in a Try-With-Resources Block

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

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) {
      // Using try-with-resources to handle the stream
      try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
         // Write data to the stream
         outputStream.write("Java Programming".getBytes());

         // Print the stream's content
         System.out.println("Data in stream: " + outputStream.toString());

         // No need to explicitly call close() because try-with-resources handles it
      } catch (IOException e) {
         System.err.println("IOException occurred: " + e.getMessage());
      }
      System.out.println("Stream closed automatically by try-with-resources.");
   }
}

Output

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

Data in stream: Java Programming
Stream closed automatically by try-with-resources.

Explanation

  • A ByteArrayOutputStream is used inside a try-with-resources block.

  • Data is written to the stream and then printed.

  • The close() method is called automatically when the try block exits, thanks to the try-with-resources construct.

  • This approach ensures proper handling of resources without requiring explicit close() calls, making the code cleaner and less error-prone.

Key Points

  • Behavior of close()

    • For ByteArrayOutputStream, calling close() has no real effect since it operates in memory.

    • The stream can still be used after closing, unlike other types of streams (e.g., FileOutputStream).

  • Good Practice

    • While closing ByteArrayOutputStream is unnecessary, it is good practice to call close() explicitly or use a try-with-resources block for consistency, especially when working with multiple streams.

  • Try-With-Resources

    • Using try-with-resources simplifies resource management and ensures that streams are closed automatically, even in the event of exceptions

  • No External Resources

    • Since ByteArrayOutputStream does not rely on external resources, you do not risk resource leaks by forgetting to close it. However, consistent resource management practices improve code readability and maintainability.

java_bytearrayoutputstream.htm
Advertisements