ByteArrayInputStream class

                                         
    java.lang.Object                                    
     |                                   
     |--java.io.InputStream                                
         |                               
         |--java.io.ByteArrayInputStream                            
                                         

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.

ConstructorSummary
ByteArrayInputStream(byte[] buf)Creates a ByteArrayInputStream so that it uses buf as its buffer array.
ByteArrayInputStream(byte[] buf, int offset, int length)Creates ByteArrayInputStream that uses buf as its buffer array.

ReturnMethodSummary
intavailable()Returns the number of remaining bytes that can be read (or skipped over) from this input stream.
voidclose()Closing a ByteArrayInputStream has no effect.
voidmark(int readAheadLimit)Set the current marked position in the stream.
booleanmarkSupported()If this InputStream supports mark/reset.
intread()Reads the next byte of data.
intread(byte[] b, int off, int len)Reads up to len bytes of data into an array of bytes from this input stream.
voidreset()Resets the buffer to the marked position.
longskip(long n)Skips n bytes of input from this input stream.
Revised from Open JDK source code

Create ByteArrayInputStream from byte array


import java.io.ByteArrayInputStream;
import java.io.IOException;

public class Main {
  public static void main(String args[]) throws IOException {
    String tmp = "abcdefghijklmnopqrstuvwxyz";
    byte b[] = tmp.getBytes();
    ByteArrayInputStream input1 = new ByteArrayInputStream(b);
    ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0, 3);
  }
}

The following code reads byte array out of ByteArrayInputStream


import java.io.ByteArrayInputStream;
import java.io.IOException;

public class Main {
  public static void main(String args[]) throws IOException {
    ByteArrayInputStream inStream = new ByteArrayInputStream(("java2s.com").getBytes());
    int inBytes = inStream.available();
    System.out.println("inStream has " + inBytes + " available bytes");
    byte inBuf[] = new byte[inBytes];
    int bytesRead = inStream.read(inBuf, 0, inBytes);
    System.out.println(bytesRead + " bytes were read");
    System.out.println("They are: " + new String(inBuf));
  }
}

The output:


inStream has 10 available bytes
10 bytes were read
They are: java2s.com
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.