Latest web development tutorials

Java ByteArrayInputStream類

字節數組輸入流在內存中創建一個字節數組緩衝區,從輸入流讀取的數據保存在該字節數組緩衝區中。 創建字節數組輸入流對像有以下幾種方式。

接收字節數組作為參數創建:

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

另一種創建方式是接收一個字節數組,和兩個整形變量off、len,off表示第一個讀取的字節,len表示讀取字節的長度。

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

成功創建字節數組輸入流對像後,可以參見以下列表中的方法,對流進行讀操作或其他操作。

序號 方法描述
1 public int read()
從此輸入流中讀取下一個數據字節。
2 public int read(byte[] r, int off, int len)
將最多len個數據字節從此輸入流讀入字節數組。
3 public int available()
返回可不發生阻塞地從此輸入流讀取的字節數。
4 public void mark(int read)
設置流中的當前標記位置。
5 public long skip(long n)
從此輸入流中跳過n個輸入字節。

實例

下面的例子演示了ByteArrayInputStream 和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();
      }
   }
}

以上實例編譯運行結果如下:

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