一、ByteArrayInputStream簡介
ByteArrayInputStream是Java.io包中的一個類,用於將byte數組轉換為一個輸入流。通過ByteArrayInputStream可以將一個byte數組轉換成一個InputStream對象,從而可以像操作流一樣操作數組。
二、ByteArrayInputStream構造函數
ByteArrayInputStream有兩個重載構造方法:
/**
* 創建一個 ByteArrayInputStream,使用 buf 作為其緩衝區數組。
*
* @param buf 緩衝區數組。
*/
public ByteArrayInputStream(byte buf[]) {
this.buf = buf;
this.pos = 0;
this.count = buf.length;
}
/**
* 創建一個 ByteArrayInputStream,使用 buf 作為其緩衝區數組,並從偏移量 offset 開始。
* 類似 {@link java.io.BufferedReader#BufferedReader(java.io.Reader, int)}。
* 參數 offset 指出 buffer 中第一個要讀取的位元組的索引;count 指出要讀取的位元組數。
*
* @param buf 緩衝區數組。
* @param offset 開始位置。
* @param count 從位置開始的要讀取的位元組數。
* @throws IllegalArgumentException 如果 {@code offset < 0} 或者 {@code count < 0} 或者 {@code offset + count} 大於數組長度。
*/
public ByteArrayInputStream(byte buf[], int offset, int count) {
Objects.checkFromIndexSize(offset, count, buf.length);
this.buf = buf;
this.pos = offset;
this.count = Math.min(offset + count, buf.length);
this.mark = offset;
}
三、ByteArrayInputStream使用案例
1、讀取byte數組內容到InputStream
第一個案例是將byte數組中的內容讀取到一個InputStream中,比如以下代碼,可以將string作為參數傳遞給getBytes()方法,返回一個byte數組,然後再將byte數組轉換為InputStream:
String string = "ByteArrayInputStream example.";
byte[] bytes = string.getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);
2、通過ByteArrayInputStream讀取位元組信息
ByteArrayInputStream可以通過read()方法讀取位元組信息,以下是一個簡單的代碼案例:
String str = "Here's a string of information!";
byte[] bytes = str.getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
int nextByte;
while ((nextByte = byteArrayInputStream.read()) != -1) {
System.out.print((char) nextByte);
}
3、通過ByteArrayInputStream跳過位元組數
我們可以通過skip()方法,在Stream里跳過指定位元組數,比如以下是跳過前5個位元組,然後列印從第6個位元組開始後面的內容:
String str = "Here's a string of information!";
byte[] bytes = str.getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
byteArrayInputStream.skip(5);
int nextByte;
while ((nextByte = byteArrayInputStream.read()) != -1) {
System.out.print((char) nextByte);
}
4、通過ByteArrayInputStream的reset()方法重新定位位元組流
reset()方法可以重新將流中最後的 mark 標記設置為 0。以下是將位元組數組中的內容讀取到第15個位元組,然後通過reset()重新定位流的讀指針位置,讀取第6個位元組及之後的內容:
String str = "Here's a string of information!";
byte[] bytes = str.getBytes();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
byteArrayInputStream.read(new byte[14], 0, 14); // 讀取到第15個位元組
byteArrayInputStream.reset(); // 定位到位元組數組開頭處
int nextByte;
while ((nextByte = byteArrayInputStream.read()) != -1) {
System.out.print((char) nextByte);
}
五、總結
ByteArrayInputStream是一個常見的輸入流,通過它可以操作byte數組。本文中介紹了ByteArrayInputStream的簡介、構造函數以及使用案例。使用ByteArrayInputStream可以幫助我們更方便的操作byte數組中的數據,提高了代碼編寫的效率。
原創文章,作者:OYOEU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/324470.html
微信掃一掃
支付寶掃一掃