Table of contents
1.
Introduction
2.
ByteArrayInputStream
2.1.
Constructors
2.2.
Methods
2.3.
Example
3.
BufferedOutputStream
3.1.
Constructors
3.2.
Methods
3.3.
Example
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

ByteArrayInputStream and ByteArrayOutputStream

Author Yashesvinee V
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

InputStream and OutputStream are abstract classes used to read or write data. A ByteArray is an array of bytes. The ByteArrayInputStream reads this Byte array as an input stream, and ByteArrayOutputStream writes data into this Byte array. Both contain an internal buffer to store data and an internal counter to keep track of the next byte to be read or written. Let’s learn about these classes in detail.

Also see,  Swap Function in Java

ByteArrayInputStream

The ByteArrayInputStream class is used to read bytes of data from a stream. Closing this stream after use has no effect as its methods can be called even after closing it without producing any IOException.

This class is a part of the java.io package and extends the InputStream class.

Declaration:

public class ByteArrayInputStream extends InputStream
You can also try this code with Online Java Compiler
Run Code

Constructors

  • ByteArrayInputStream(byte[ ] b)

    • It creates ByteArrayInputStream to use b as its buffer array. It reads the entire data from this array.
       
ByteArrayInputStream ba_in = new ByteArrayInputStream(byte[] b);
You can also try this code with Online Java Compiler
Run Code

 

  • ByteArrayInputStream(byte [ ] b, int offset, int length)

    • It creates ByteArrayInputStream to use b as its buffer array. It reads a specific number of bytes from a particular starting point in the array.
       
ByteArrayInputStream ba_in = new ByteArrayInputStream(byte[] b, int offset, int length);
You can also try this code with Online Java Compiler
Run Code

Methods

Method

Description

int available() It returns the estimated number of bytes that can be read or skipped over from this input stream without blocking calls from another method that requests this InputStream.
void close() It closes the InputStream and releases all the resources associated with it.
void mark (int readLimit) It marks a point in the input stream.
Boolean markSupported() It checks if the input stream supports the mark and reset functions.
int read() It reads the next byte of data from the Input stream.
int read (byte b[ ], int off, int len) It reads a given number of bytes from the Input stream and stores it in the given byte array.
void reset() It resets the position of the stream to the initial one mentioned by the most recent mark function.
long skip(long n) It skips over and discards n bytes of data from the Input stream.

Example

import java.io.ByteArrayInputStream;

public class Main {
  public static void main(String[] args) {

    byte[] arr = {'a','b','c'};

    try {
      // Create input stream
      ByteArrayInputStream input = new ByteArrayInputStream(arr);

      System.out.println(input.markSupported());
      System.out.println(input.available());

      for(int i= 0; i < arr.length; i++) {

        // Read the bytes
        int data = input.read();
        System.out.print(data + " ");
      }
      input.close();
    }

    catch(Exception e) {
      System.out.println(e);
    }
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

true
3
97 98 99


Try it on online java compiler.

BufferedOutputStream

The ByteArrayOutputStream class is used to write bytes of data into a byte array via an output stream. The default size of the buffer is 32 bytes and automatically increases as data is written into it. Closing this stream after use has no effect as its methods can be called even after closing it without producing any IOException.

This class is a part of the java.io package and extends the OutputStream class.

Declaration:

public class ByteArrayOutputStream extends OutputStream
You can also try this code with Online Java Compiler
Run Code

Constructors

  • ByteArrayOutputStream()

    • It creates a new ByteArrayOutputStream.
       
ByteArrayOutputStream ba_out = new ByteArrayOutputStream();
You can also try this code with Online Java Compiler
Run Code

 

  • ByteArrayOutputStream(int size)

    • It creates a new ByteArrayOutputStream with a specific size for the buffer array.
       
ByteArrayOutputStream ba_out = new ByteArrayOutputStream(int size);
You can also try this code with Online Java Compiler
Run Code

Methods

Method

Description

void close() It closes the ByteArrayOutputStream, which has no effect.
void reset() It resets the count field if the byte array input stream to zero. This action discards all the present content of the output stream.
int size() It returns the current size of the buffer.
byte[ ] toByteArray It creates a newly allocated byte array.
void write(byte b[ ], int off, int len) It writes a given number of bytes from the byte array into the output stream.
void write (int b) It writes a specific byte into the buffered input stream.
String toString() It converts the contents of the buffer into a string by using the default character set.
void writeTo(OutputStream out) It writes all the contents of the byte array output stream into the specified output stream that is passed as an argument.

Example

import java.io.ByteArrayOutputStream;

class Main {
  public static void main(String[] args) {

    String data = "Hello world!!!";

    try {
      // Create an output stream
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] array = data.getBytes();

      // Write data to the output stream
      out.write(array);
      System.out.println("Current size of the buffer: " + out.size());
      
      // Use toByteArray()
      System.out.println("Characters are: ");
      for(byte b: out.toByteArray())
      System.out.print((char)b + ", ");
      
      // Retrieve data from the output stream in string format
      String stream = out.toString();
      System.out.println("\nOutput stream: " + stream);

      out.close();
    }

    catch(Exception e) {
      System.out.println(e);
    }
  }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Current size of the buffer: 14
Characters are: 
H, e, l, l, o,  , w, o, r, l, d, !, !, !, 
Output stream: Hello world!!!

Check out this problem - Search In Rotated Sorted Arra, Duck Number in Java and Hashcode Method in Java

FAQs

  1.  What is a stream?
    A Stream is a logical connection between the Java program and a file that is used to exchange a sequence of bytes. Based on the direction of data flow, it could be an Input stream or Output stream to read inputs and deliver outputs, respectively. 
     
  2.  What is the difference between ByteArrayOutputStream and BufferedOutputStream?
    ByteArrayOutputStream writes bytes of data to a byte array in memory and not to any destination file or folder. The BufferedOutputStream wraps an underlying OutputStream and provides a buffer to make I/O operations more efficient.

Key Takeaways

This article extensively discusses the ByteArrayInput/OutputStream classes in Java. We hope that this blog has helped you enhance your knowledge regarding the constructors and methods of ByteArrayInput/OutputStream classes and if you would like to learn more, check out our articles on the Coding Ninjas Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Related Links:

Input and Output Streams in C++

File operations

Live masterclass