Java I/O Streams: ByteArrayInputStream and ByteArrayOutputStream
In this blog, we will explore ByteArrayInputStream and ByteArrayOutputStream, two memory-based I/O stream classes in Java. These classes are useful when working with byte arrays instead of files or external data sources.
1. What Are ByteArrayInputStream and ByteArrayOutputStream?#
- ByteArrayInputStream allows an application to read data from a byte array as an input stream.
- ByteArrayOutputStream allows writing data to a byte array, which grows automatically.
These streams are often used in testing, conversions, or working with binary data in memory without accessing the filesystem.
2. ByteArrayInputStream Methods (With Examples)#
● int read()
#
Reads the next byte of data from the input stream.
Output:#
● int read(byte[] b, int off, int len)
#
Reads up to len
bytes into b
starting from offset off
.
Output:#
● int available()
#
Returns the number of remaining bytes that can be read.
Output:#
● void reset()
#
Resets the stream to the beginning.
Output:#
3. ByteArrayOutputStream Methods (With Examples)#
● void write(int b)
#
Writes a single byte to the output stream.
Output:#
● void write(byte[] b)
#
Writes a byte array to the stream.
Output:#
● byte[] toByteArray()
#
Returns the current contents as a byte array.
Output:#
● void reset()
#
Clears the current buffer.
Output:#
4. When to Use ByteArrayInputStream and ByteArrayOutputStream?#
- Use ByteArrayInputStream when reading from an in-memory byte array instead of from an external file.
- Use ByteArrayOutputStream when you want to collect bytes in memory and optionally convert them to a byte array or string.
- These are great for data conversion, unit testing, and mocking file I/O in memory.
Conclusion#
In this blog, we covered ByteArrayInputStream and ByteArrayOutputStream, their commonly used methods, and practical examples with outputs. These memory-based streams are powerful tools for manipulating byte data directly in RAM, making them very useful in a variety of situations such as testing or data transformation.
In the next blog, we'll cover ObjectInputStream and ObjectOutputStream, which are used to serialize and deserialize Java objects.