Read bytes ByteArrayInputStream


Reading Byte Array Partially

In the earlier program, all the bytes are read and now let us try to read a few from the array.

import java.io.*;
public class BAInput1
{
  public static void main(String args[]) throws IOException
  {
    byte alphabets[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G'  };
    ByteArrayInputStream bai = new ByteArrayInputStream(alphabets, 2, 4);
    int temp;
    System.out.println("Reading 4 bytes from 2nd alphabet (actullay it is 3): ");

    while((temp = bai.read()) != -1)
    {
      char ch1 = (char) temp;
      System.out.println("Original character: " + ch1 + " and its ASCII value: " + temp);
    }
    bai.close();
   }
}


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

byte alphabets[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
ByteArrayInputStream bai = new ByteArrayInputStream(alphabets, 2, 4);

The whole byte array alphabets is passed to the constructor of ByteArrayInputStream. The characters read are 4 from the offset 2 (index numbering begins from 0); that is, the characters read are, C, D, E, and F.

Leave a Comment

Your email address will not be published.