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