
- Java.io - Home
- Java.io - BufferedInputStream
- Java.io - BufferedOutputStream
- Java.io - BufferedReader
- Java.io - BufferedWriter
- Java.io - ByteArrayInputStream
- Java.io - ByteArrayOutputStream
- Java.io - CharArrayReader
- Java.io - CharArrayWriter
- Java.io - Console
- Java.io - DataInputStream
- Java.io - DataOutputStream
- Java.io - File
- Java.io - FileDescriptor
- Java.io - FileInputStream
- Java.io - FileOutputStream
- Java.io - FilePermission
- Java.io - FileReader
- Java.io - FileWriter
- Java.io - FilterInputStream
- Java.io - FilterOutputStream
- Java.io - FilterReader
- Java.io - FilterWriter
- Java.io - InputStream
- Java.io - InputStreamReader
- Java.io - LineNumberInputStream
- Java.io - LineNumberReader
- Java.io - ObjectInputStream
- Java.io - ObjectInputStream.GetField
- Java.io - ObjectOutputStream
- io - ObjectOutputStream.PutField
- Java.io - ObjectStreamClass
- Java.io - ObjectStreamField
- Java.io - OutputStream
- Java.io - OutputStreamWriter
- Java.io - PipedInputStream
- Java.io - PipedOutputStream
- Java.io - PipedReader
- Java.io - PipedWriter
- Java.io - PrintStream
- Java.io - PrintWriter
- Java.io - PushbackInputStream
- Java.io - PushbackReader
- Java.io - RandomAccessFile
- Java.io - Reader
- Java.io - SequenceInputStream
- Java.io - SerializablePermission
- Java.io - StreamTokenizer
- Java.io - StringBufferInputStream
- Java.io - StringReader
- Java.io - StringWriter
- Java.io - Writer
- Java.io package Useful Resources
- Java.io - Discussion
Java - ByteArrayOutputStream Class
Introduction
The Java ByteArrayOutputStream class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.Following are the important points about ByteArrayOutputStream −
Closing a ByteArrayOutputStream has no effect.
The methods in this class can be called after the stream has been closed without generating an IOException.
Class declaration
Following is the declaration for Java.io.ByteArrayOutputStream class −
public class ByteArrayOutputStream extends OutputStream
Field
Following are the fields for Java.io.ByteArrayOutputStream class −
protected byte[] buf − This is the buffer where data is stored.
protected int count − This is the number of valid bytes in the buffer.
Class constructors
Sr.No. | Constructor & Description |
---|---|
1 |
ByteArrayOutputStream() This creates a new byte array output stream. |
2 |
ByteArrayOutputStream(int size) This creates a new byte array output stream, with a buffer capacity of the specified size, in bytes. |
Class methods
Sr.No. | Method & Description |
---|---|
1 |
void close()
Closing a ByteArrayOutputStream has no effect. |
2 |
void reset()
This method resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded. |
3 |
int size()
This method returns the current size of the buffer. |
4 |
byte[] toByteArray()
This method creates a newly allocated byte array. |
5 |
String toString()
This method converts the buffer's contents into a string decoding bytes using the platform's default character set. |
6 |
String toString(String charsetName)
This method converts the buffer's contents into a string by decoding the bytes using the specified charsetName. |
7 |
void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to this byte array output stream. |
8 |
void write(int b)
This method Writes the specified byte to this byte array output stream. |
9 |
void writeTo(OutputStream out)
This method writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count). |
Methods inherited
This class inherits methods from the following classes −
- Java.io.OutputStream
- Java.io.Object
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.
Example - Using reset() to Reuse the Stream
The following example shows the usage of Java ByteArrayInputStream reset() 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, World!".getBytes()); System.out.println("First output: " + outputStream.toString()); // Reset the stream to clear the buffer outputStream.reset(); System.out.println("Stream reset."); // Write new data to the same stream outputStream.write("Java Programming".getBytes()); System.out.println("Second output: " + 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 −
First output: Hello, World! Stream reset. Second output: Java Programming
Explanation
A ByteArrayOutputStream is created.
The first string, "Hello, World!", is written to the stream and printed.
The reset() method is called, which clears the buffer and makes the stream empty again.
The second string, "Java Programming", is written to the same stream after resetting it.
The new content of the stream is printed, showing that the previous data has been discarded.
Example - Using toByteArray() to Retrieve Data from the Stream
The following example shows the usage of Java ByteArrayInputStream toByteArray() method.
ByteArrayOutputStreamDemo.java
package com.tutorialspoint; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; 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, World!".getBytes()); // Convert the stream content to a byte array byte[] byteArray = outputStream.toByteArray(); // Print the byte array System.out.println("Byte array: " + Arrays.toString(byteArray)); // Convert the byte array back to a string and print it String content = new String(byteArray); System.out.println("String content: " + content); // 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 −
Byte array: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33] String content: Hello, World!
Explanation
The string "Hello, World!" is written to the ByteArrayOutputStream.
The toByteArray() method is called to retrieve the content of the stream as a new byte array.
The byte array is printed using Arrays.toString() for better visualization of the raw byte data.
The byte array is converted back to a string using the String constructor to demonstrate how the data can be reused.
Although calling close() on a ByteArrayOutputStream has no real effect, it is included for consistency.