Java-ByteArrayInputStream

ByteArrayInputStream

ByteArrayInputStream class contains an internal buffer which is used to read byte array as stream. In this stream, the data is read from a byte array. Being a subclass of InputStream the ByteArrayInputStream also has a close( ) method. But calling the close( ) method has no effect on the ByteArrayInputStream.

ByteArrayInputStream Constructors

Constructors Description
ByteArrayInputStream(byte[] buf) Creates a new byte array input stream which uses ‘buf’ as its buffer array.
ByteArrayInputStream(byte[] buf, int offset, int length) Creates a new byte array input stream which uses ‘buf’ as its buffer array that can read up to specified ‘length’ bytes of data from an array.

ByteArrayInputStream Methods

Method Description
int read() Reads the next byte of data from the InputStream. Returns an int as the next byte of data. If it is the end of the file, then it returns -1.
int read(byte[] b) Reads upto b.length bytes of data from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned.
int read(byte[] b, int off, int len) Reads upto ‘len’ number of bytes starting from ‘off’ from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned.
int available() Return the number of remaining bytes that can be read from the input stream.
long skip(long n) Skip the ‘n’ bytes of input from the input stream.
boolean markSupported() Tells whether this stream supports the mark() operation, which it does.
void mark(int readAheadLimit) Sets the current marked position in the stream. The parameter gives the maximum limit of bytes that can be read before the marked position becomes invalid.
void reset() Resets the stream to the most recent mark, or to the beginning of the string if it has never been marked.
void close() Being a subclass of OutputStream the ByteArrayInputStream also has a close( ) method. But calling the close() method has no effect on the ByteArrayOutputStream.

Program

ByteArrayInputStream

Program Source

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class Javaapp {
    
    public static void main(String[] args) throws IOException {
        
        byte bya[] = {60,70,80,90,100,10,20,30,40,50,120};
        ByteArrayInputStream bis = new ByteArrayInputStream(bya);
        System.out.println("Avb : "+bis.available());
        bis.skip(5);
        System.out.println("Avb : "+bis.available());
        
        byte byte1[] = new byte[5];
        bis.read(byte1);
        for(byte by : byte1)
        {
            System.out.print("["+by+"] ");
        }  
        System.out.println();
        bis.reset();
        System.out.println("Avb : "+bis.available());
        
        byte byte2[] = new byte[5];
        bis.read(byte2);
        for(byte by : byte2)
        {
            System.out.print("["+by+"] ");
        }
    }
}

Leave a Comment