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.

import java.io.*;
public class BAInput
{
  public static void main(String args[]) throws IOException
  {
    byte vowels[] = { 'a', 'e', 'i', 'o', 'u' };
    ByteArrayInputStream bai = new ByteArrayInputStream(vowels);
    int temp;
    while(( temp = bai.read()) != -1)
    {
      char ch = (char) temp;
      System.out.println("Vowel: " + ch + " and its ASCII value: " + temp);
    }

    System.out.println("\n\nTo read again after calling reset() method");
    bai.reset();   // places the file poiner at the beginning of the array
    while( ( temp = bai.read() ) != -1)
    {
      char ch = (char) temp;
      System.out.println("Vowel: " + ch + " and its ASCII value: " + temp);
    }
    bai.close();
   }
}


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 Comment

Your email address will not be published.