PUBLISHED ON: MAY 1, 2021
Java ByteArrayInputStream read() Method
In this tutorial, we will learn about the read()
method of the ByteArrayInputStream class in Java. This method reads the next byte of the ByteArrrayInputStream and it reads only one byte at a time from the stream. It is a non-static method, available in the java.io package, which should only be accessed using class objects. It may throw an exception while reading the bytes.
Syntax:
This is the syntax declaration of this method. It does not accept any parameter and it returns the byte which is read in the form of an integer. If it reaches the end of the stream, it will return -1.
public int read()
Example: ByteArrayInputStream read() Method
We use the read() method to read the data from the buffer, this method will return the integer in the format of ASCII code if the data is in the form of characters then we need to typecase accordingly.
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight
{
public static void main(String[] args) throws IOException
{
byte[] buf = {1, 2, 3, 4, 5};
ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(buf);
int b = 0;
while ((b = byteArrayInputStr.read()) != -1)
{
System.out.print(" " + b);
}
}
}
1 2 3 4 5
Example: ByteArrayInputStream read() Method
Here we are using another overloading method of the read method it accepts the three parameters first one is buffer where we want to store the data then the second one is the starting position of from where it will start reading we also call it the offset and third parameter will the length of the data.
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class StudyTonight
{
public static void main(String[] args) throws IOException
{
byte[] buf = {4, 8, 12, 16};
ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(buf);
byte[] b = new byte[2];
int total_bytes = byteArrayInputStr.read(b, 0, 2);
System.out.println("Total bytes read: " + total_bytes);
for (byte ch : b)
{
System.out.print(ch+" ");
}
}
}
Total bytes read: 2
4 8
Conclusion:
In this tutorial, we learned about the read()
method of the ByteArrayInputStream class in Java, which is used to read the next byte of the current input stream reading one byte at a time, and returns the byte read in the form of an integer, or -1 if the end of the stream is reached.