Java ByteArrayInputStream類

ByteArrayInputStream類用於將記憶體中的緩衝區用作為InputStream。輸入源是一個位元組數組。

ByteArrayInputStream類提供以下構造函數。

編號 方法 描述
1 ByteArrayInputStream(byte [] a) 此構造函數接受位元組數組作為參數。
2 ByteArrayInputStream(byte [] a, int off, int len) 此構造函數採用一個位元組數組和兩個整數值,其中off是要讀取的第一個位元組,len是要讀取的位元組數。

當創建了ByteArrayInputStream對象,就可以使用一些它的輔助方法來讀取流或在流上執行其他操作。

編號 方法 描述
1 public int read() 此方法從InputStream讀取下一個數據字節。 返回一個int值作為數據的下一個位元組。 如果它是檔的結尾,則返回-1
2 public int read(byte[] r, int off, int len) 此方法讀取從輸入流關閉到數組的最多len個位元組數。返回讀取的總位元組數。如果它是檔的結尾,則返回-1
3 public int available() 給出可以從此檔輸入流中讀取的位元組數。 返回一個int值,它給出了要讀取的位元組數。
4 public void mark(int read) 這將設置流中當前標記的位置。 該參數給出了在標記位置變為無效之前可以讀取的最大字節數限制。
5 public long skip(long n) 從流中跳過n個位元組,它將返回實際跳過的位元組數。

示例

以下是演示ByteArrayInputStreamByteArrayOutputStream的示例。

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("hello".getBytes());
      }
      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("將字母轉為大寫 >" );

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

執行上面示例代碼,得到以下結果:

Print the content
h   e   l   l   o   h   e   l   l   o
將字母轉為大寫 >
H
E
L
L
O
H
E
L
L
O

上一篇: Java檔和輸入和輸出(I/O) 下一篇: Java快速入門