1. 程式人生 > >JAVA 快取陣列之----ByteArrayInputStream類詳解

JAVA 快取陣列之----ByteArrayInputStream類詳解

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