Java.io.ByteArrayInputStream.read() Method
Advertisements
Description
The java.io.ByteArrayInputStream.read() method reads the next byte from this input stream. The read() method doesn't block
Declaration
Following is the declaration for java.io.ByteArrayInputStream.read() method:
public int read()
Parameters
NA
Return Value
Returns value byte as int in the range 0-255. Returns -1 if the stream has reached it's end.
Exception
NA
Example
The following example shows the usage of java.io.ByteArrayInputStream.read() 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);
int b =0;
// read till the end of the stream
while((b = bais.read())!=-1)
{
// convert byte to character
char c = (char)b;
// print
System.out.println("byte :"+b+"; char : "+ c);
}
System.out.print(bais.read()+" Reached the end");
}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:
byte :65; char : A byte :66; char : B byte :67; char : C byte :68; char : D byte :69; char : E -1 Reached the end