Read bytes ByteArrayInputStream

Read bytes ByteArrayInputStream

Read bytes ByteArrayInputStream

Summary: By the end of this tutorial "Read bytes ByteArrayInputStream", you will come to know to read a byte array. The byte array can be read fully or a few elements. Two separate programs given.

This class is very useful to read data from byte arrays. For example, in UDP protocol, the data is received in byte array and ByteArrayInputStream is helpful to read data from this array. The data can be read completely from the array or partially from any offset (jumping to any position in the array and read the data from that position).

Here, two programs are given that read data fully from a byte array and the other partially.

Reading fully from a Byte Array

In this program, the data is read fully from the byte array. Each byte is read and printed along with its ASCII value.


Read bytes ByteArrayInputStream
Output screen of BAInput.java of Read bytes ByteArrayInputStream

ByteArrayInputStream bai = new ByteArrayInputStream(vowels);

The byte array vowels is passed as parameter to the ByteArrayInputStream constructor.

temp = bai.read()
char ch = (char) temp;

The read() method of ByteArrayInputStream (inherited from its super class, InputStream) reads byte by byte from the array, converts the each byte into its ASCII integer value and returns. For example, the read() method reads 'a' and returns it as 97. To print the original character, the temp variable is explicitly type casted to char ch.

bai.reset();

The reset() method places the file pointer at the beginning of the array, so that, if necessary we can read the data again. The same thing is done in the program; the data is read again and printed (same output).

byte vowels[] = { 'a', 'e', 'i', 'o', 'u' };

The above statement can be replaced with the following (where ASCII values are taken instead of characters) and can be obtained the same output.

byte vowels[] = { 97, 101, 105, 111, 117 };

Leave a Reply

Your email address will not be published. Required fields are marked *