Java ByteArrayInputStream create from byte array

Introduction

ByteArrayInputStream implements input stream and uses a byte array as the source.

This class has two constructors:

ByteArrayInputStream(byte array [ ])  
ByteArrayInputStream(byte array [ ], int start, int numBytes) 

The close() method has no effect on a ByteArrayInputStream.

// Demonstrate ByteArrayInputStream. 
import java.io.*; 
 
public class Main { 
  public static void main(String args[]) { 
    String tmp = "abcdefghijklmnopqrstuvwxyz"; 
    byte b[] = tmp.getBytes(); 
 
    ByteArrayInputStream input1 = new ByteArrayInputStream(b); 
    ByteArrayInputStream input2 = new ByteArrayInputStream(b,0,3); 
  } /*from w  w  w .  j a  v a  2  s  .  com*/
}

The following example shows how to use the reset() method to read the same input twice.

import java.io.ByteArrayInputStream;

public class Main {
  public static void main(String args[]) {
    String tmp = "abc";
    byte b[] = tmp.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream(b);

    int c;//from   ww w .j a v a2s .  c o m
    while ((c = in.read()) != -1) {
      System.out.print((char) c);
    }
    System.out.println();
    in.reset();

    // again
    while ((c = in.read()) != -1) {
      System.out.print((char) c);
    }
    System.out.println();
    in.reset();

  }
}



PreviousNext

Related