Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java ByteArrayInputStream Class

In this tutorial, we will learn about ByteArrayInputStream class in Java. This class is used to read an array of the byte as an input stream.

The buffer size of ByteArrayInputStream automatically grows according to data.

Syntax

This is the syntax declaration of ByteArrayInputStream class and we can see it inherits InputStream class.

public class ByteArrayInputStream extends InputStream  

Java ByteArrayInputStream class Constructors

Constructors of this class are given below in the table.

Constructor Description
ByteArrayInputStream(byte[] ary) Creates a new byte array input stream that uses ary as its buffer array.
ByteArrayInputStream(byte[] ary, int offset, int len) Creates a new byte array input stream that uses ary as its buffer array that can read up to specified len bytes of data from an array.

Java ByteArrayInputStream class Methods

Various methods of this class are mentioned below.

Methods Description
int available() This method is used to return the number of remaining bytes that can be read from the input stream.
int read() This method is used to read the next byte of data from the input stream.
int read(byte[] ary, int off, int len) This method is used to read up to len bytes of data from an array of bytes in the input stream.
boolean markSupported() This method is used to test the input stream for mark and reset method.
long skip(long x) This method is used to skip the x bytes of input from the input stream.
void mark(int readAheadLimit) This method is used to set the currently marked position in the stream.
void reset() This method is used to reset the buffer of a byte array.
void close() This method is used for closing a ByteArrayInputStream.

Example of Java ByteArrayInputStream

In the following code, we are demonstrating how ByteArrayInputStream class works. Here we are reading each element from an array of byte using read() method of this class and printing it by typecasting to char because by default it will bread as an ASCII code.

import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{  
		byte[] buf = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};  
		ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(buf);  
		int ch = 0;  
		while ((ch = byteArrayIS.read()) != -1) 
		{  
			System.out.print((char) ch); 
		}    
	}  
}


abcdefg

Conclusion:

In this article, we learned about ByteArrayInputStream class, this class is used to read byte array as a stream. The buffer size of ByteArrayInputStream automatically grows according to data.