Java - ByteArrayOutputStream size() method



Description

The Java ByteArrayOutputStream size() method is used to return the current size of the buffer, which corresponds to the number of bytes written to the stream. It is helpful for determining the amount of data in the stream at any given time.

Declaration

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

public int size()

Parameters

NA

Return Value

The method returns the current size of the buffer accumulated inside the output stream.

Exception

NA

Example - Using ByteArrayOutputStream size() method

The following example shows the usage of Java ByteArrayOutputStream size() method. We've created a ByteArrayOutputStream reference and then initialized it with ByteArrayOutputStream object. Now we write a value to output stream in a for loop and print the stream using toString() method and its size using size() method. Lastly in finally block, we close the stream using close() method.

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

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

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      String str = "";
      int size = 0;            
      byte[] bs = {65, 66, 67, 68, 69};
      ByteArrayOutputStream baos = null;
      
      try {
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();
      
         // for each byte in the buffer
         for (byte b : bs) {
         
            // write byte in to output stream
            baos.write(b);
            
            // convert output stream to string
            str = baos.toString();
            size = baos.size();
            
            // print
            System.out.print(size+":");
            System.out.println(str);
         }
         
      } 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 −

1:A
2:AB
3:ABC
4:ABCD
5:ABCDE

Example - Using ByteArrayOutputStream size() method

The following example shows the usage of Java ByteArrayOutputStream size() method. We've created a ByteArrayOutputStream reference and then initialized it with ByteArrayOutputStream object. Now we're writing multiple value to output stream and print the stream using toString() method and its size using size() method. As a next step, we've reset the output stream to be empty and printed it again and its size using size() method.

ByteArrayOutputStreamDemo.java

package com.tutorialspoint;

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

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      ByteArrayOutputStream baos = null;      
      try {
         String str = "";
         
         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();
         
         // writing bytes to output stream
         baos.write(75);
         baos.write(65);
         
         // output stream to string
         str = baos.toString();
         System.out.println("Before Resetting : "+str);
         System.out.println("Stream Size : "+baos.size());
         
         // reset() method invocation 
         baos.reset();
         
         // output stream to string()
         str = baos.toString();
         System.out.println("After Resetting : "+ str);
         System.out.println("Stream Size : "+baos.size());
      } 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 −

Before Resetting : KA
Stream Size : 2
After Resetting : 
Stream Size : 0

Example - Using size() to Get the Buffer Size

The following example shows the usage of Java ByteArrayInputStream size() 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 stream
         outputStream.write("Hello".getBytes());
         System.out.println("Current size after writing 'Hello': " + outputStream.size());

         // Write more data to the stream
         outputStream.write(", World!".getBytes());
         System.out.println("Current size after writing ', World!': " + outputStream.size());

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

         // Close the stream (optional for ByteArrayOutputStream)
         outputStream.close();
      } 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 −

Current size after writing 'Hello': 5
Current size after writing ', World!': 13
Stream content: Hello, World!

Explanation

  • Write Operation

    • Data ("Hello") is written to the ByteArrayOutputStream, and the size of the buffer is printed using the size() method.

    • The size will equal the number of bytes in the string "Hello" (5 bytes).

  • Additional Write Operation

    • More data (", World!") is written to the stream, and the size of the buffer is printed again.

    • The new size reflects the combined number of bytes from "Hello, World!" (13 bytes).

  • Buffer Content

    • The stream's content is converted to a string and printed using the toString() method.

  • Closing

    • The close() method is called at the end, although it has no real effect for ByteArrayOutputStream.

Key Points

  • Purpose

    • The size() method provides the number of bytes written to the stream, allowing you to monitor or track data usage.

  • Real-Time Buffer Size

    • You can use size() at any point to check the current size of the buffer.

  • Use Case

    • This is useful when working with dynamic data or when you want to ensure the buffer doesn't exceed a certain limit.

  • Internal Behavior

    • The size reported by size() reflects the actual number of bytes written to the stream, but it does not account for unused capacity in the buffer.

java_bytearrayoutputstream.htm
Advertisements