Java ByteArrayInputStream Class

Java 流(Stream)Java Stream


The byte array input stream creates a byte array buffer in memory, and the data read from the input stream is stored in this byte array buffer. There are several ways to create a byte array input stream object.

Create by accepting a byte array as a parameter:

ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);

Another way to create it is to accept a byte array and two integer variables, off and len, where off represents the first byte to be read and len represents the length of bytes to be read.

ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, 
                                                       int off, 
                                                       int len)

After successfully creating a byte array input stream object, you can refer to the methods in the following list to perform read operations or other operations on the stream.

No. Method Description
1 public int read()       
Reads the next data byte from this input stream.
2 public int read(byte[] r, int off, int len)
Reads up tolendata bytes from this input stream into a byte array.
3 public int available()
Returns the number of bytes that can be read from this input stream without blocking.
4 public void mark(int read)
Sets the current marked position in the stream.
5 public long skip(long n)
Skips overninput bytes from this input stream.

Example

The following example demonstrates the use of ByteArrayInputStream and ByteArrayOutputStream:

import java.io.*;

public class ByteStreamTest {

   public static void main(String args[])throws IOException {

      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ) {
         // 获取用户输入值
         bOutput.write(System.in.read());
      }

      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      for(int x= 0 ; x < b.length; x++) {
         // 打印字符
         System.out.print((char)b[x]  + "   ");
      }
      System.out.println("   ");

      int c;

      ByteArrayInputStream bInput = new ByteArrayInputStream(b);

      System.out.println("Converting characters to Upper case " );
      for(int y = 0 ; y < 1; y++ ) {
         while(( c= bInput.read())!= -1) {
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset();
      }
   }
}

The output of the above example is as follows:

asdfghjkly
Print the content
a   s   d   f   g   h   j   k   l   y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y

Java 流(Stream)Java Stream

Other Extensions