Java - ByteArrayInputStream 類及示例



java.io.ByteArrayInputStream 類包含一個內部緩衝區,其中包含可從流中讀取的位元組。一個內部計數器跟蹤由 read 方法提供的下一個位元組。以下是關於 ByteArrayInputStream 的一些重要要點:

  • 關閉 ByteArrayInputStream 不會有任何影響。

  • 即使流已關閉,此類中的方法也可以被呼叫,而不會產生 IOException。

類宣告

以下是 java.io.ByteArrayInputStream 類的宣告:

public class ByteArrayInputStream
   extends InputStream

欄位

以下是 java.io.ByteArrayInputStream 類的欄位:

  • protected byte[] buf - 這是由流建立者提供的位元組陣列。

  • protected int count - 這是輸入流緩衝區中最後一個有效字元後一個的索引。

  • protected int mark - 這是流中當前標記的位置。

  • protected int pos - 這是要從輸入流緩衝區讀取的下一個字元的索引。

類建構函式

序號 建構函式及描述
1

ByteArrayInputStream(byte[] buf)

建立一個 ByteArrayInputStream,使用 buf 作為其緩衝區陣列。

2

ByteArrayInputStream(byte[] buf, int offset, int length)

建立一個 ByteArrayInputStream,使用 buf 作為其緩衝區陣列。

類方法

序號 方法及描述
1 int available()

此方法返回可以從此輸入流讀取(或跳過)的剩餘位元組數。

2 void close()

關閉 ByteArrayInputStream 不會有任何影響。

3 void mark(int readAheadLimit)

此方法設定流中當前標記的位置。

4 boolean markSupported()

此方法測試此 InputStream 是否支援 mark/reset。

5 int read()

此方法讀取從此輸入流中的下一個資料位元組。

6 int read(byte[] b, int off, int len)

此方法最多讀取 len 個位元組的資料到此輸入流中的位元組陣列中。

7 void reset()

此方法將緩衝區重置到標記的位置。

8 long skip(long n)

此方法跳過從此輸入流中的 n 個輸入位元組。

繼承的方法

此類繼承自以下類的方法:

  • java.io.InputStream
  • java.io.Object

示例

以下示例演示了 ByteArrayInputStream 和 ByteArrayOutputStream 的用法。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteStreamTest {
   public static void main(String args[])throws IOException {
      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
      while( bOutput.size()!= 10 ) {
         
         // Gets the inputs from the user
         bOutput.write("hello".getBytes()); 
      }
      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");      
      for(int x = 0 ; x < b.length; x++) {
         
         // printing the characters
         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(); 
      }
   }
}

輸出

Print the content
h   e   l   l   o   h   e   l   l   o      
Converting characters to Upper case 
H
E
L
L
O
H
E
L
L
O
java_files_io.htm
廣告

© . All rights reserved.