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 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.
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() Reset the buffer of a byte array.
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, 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.

Program

21

Program Source

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

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

Leave a Comment