Skip to Content

Read partial byte array using ByteArrayInputStream Example

  1. /*
  2.         Read partial byte array using ByteArrayInputStream Example
  3.         This example shows how to create ByteArrayInputStream from
  4.         partial array of bytes using offset and legth arguments of
  5.         ByteArrayInputStream constructor.
  6.        
  7.         Method of this class can be called even after calling the close method
  8.         without causing the IOException. Closing ByteArrayInputStream has
  9.         no effect.
  10.        
  11. */
  12.  
  13. import java.io.ByteArrayInputStream;
  14.  
  15. public class ReadPartialByteArray {
  16.  
  17.         public static void main(String[] args) {
  18.                
  19.                 String str = "Byte Array InputStream Example";
  20.                
  21.                 //get bytes from string
  22.                 byte[] bytes = str.getBytes();
  23.                
  24.                 /*use below given constructor of ByteArrayInputStream to
  25.                  * create stream of partial byte array,
  26.                  *
  27.                  * ByteArrayInputStream(byte[] b, int offset, int length)
  28.                  */
  29.                  
  30.                  ByteArrayInputStream bis = new ByteArrayInputStream(bytes, 5, 5);
  31.                  int ch;
  32.                  
  33.                  while ((ch = bis.read()) != -1)
  34.                  {
  35.                         System.out.print((char)ch);
  36.                  }
  37.                
  38.         }
  39. }
  40.  
  41. /*
  42. Output of this program would be
  43. Array
  44. */