Java.io.ByteArrayInputStream.read() Method
Description
The java.io.ByteArrayInputStream.read(byte[] b, int off, int len) method reads len bytes of data from this input stream into an array of bytes. The read() method doesn't block
Declaration
Following is the declaration for java.io.ByteArrayInputStream.read(byte[] b, int off, int len) method:
public int read(byte[] b, int off, int len)
Parameters
b -- data is read into this buffer
off -- Offset to start at destination array b
len -- maximum number of bytes read
Return Value
Number of bytes read into the buffer. Returns -1 if the stream has reached it's end.
Exception
NullPointerException -- If b is null.
IndexOutOfBoundsException -- If len is greater than input stream's length after offset, off is negative, or len is negative.
Example
The following example shows the usage of java.io.ByteArrayInputStream.read(byte[] b, int off, int len) method.
package com.tutorialspoint;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteArrayInputStreamDemo {
public static void main(String[] args) throws IOException {
byte[] buf = {65, 66, 67, 68, 69};
ByteArrayInputStream bais = null;
try{
// create new byte array input stream
bais = new ByteArrayInputStream(buf);
// create buffer
byte[] b = new byte[4];
int num = bais.read(b, 2, 2);
// number of bytes read
System.out.println("Bytes read: "+num);
// for each byte in a buffer
for (byte s :b)
{
// covert byte to char
char c = (char)s;
// prints byte
System.out.print(s);
if(s==0)
// if byte is 0
System.out.println(": Null");
else
// if byte is not 0
System.out.println(": "+c);
}
}catch(Exception e){
// if I/O error occurs
e.printStackTrace();
}finally{
if(bais!=null)
bais.close();
}
}
}
Let us compile and run the above program, this will produce the following result:
Bytes read: 2 0: Null 0: Null 65: A 66: B