Java ByteArrayOutputStream 內存輸出流
概述
- 此類實現了一個輸出流,其中的數據被寫入一個 byte 數組。緩衝區會隨着數據的不斷寫入而自動增長。可使用 toByteArray() 和 toString() 獲取數據
ByteArrayOutputStream
構造方法 |
說明 |
ByteArrayOutputStream() |
創建一個新的 byte 數組輸出流 |
ByteArrayOutputStream(int size) |
創建一個新的 byte 數組輸出流,它具有指定大小的緩衝區容量(以字節爲單位) |
方法 |
說明 |
write(int b) |
將指定的字節寫入此 byte 數組輸出流 |
write(byte[] b, int off, int len) |
將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此 byte 數組輸出流 |
toByteArray() |
創建一個新分配的 byte 數組 |
toString() |
使用平臺默認的字符集,通過解碼字節將緩衝區內容轉換爲字符串 |
toString(String charsetName) |
使用指定的 charsetName,通過解碼字節將緩衝區內容轉換爲字符串 |
讀取文件示例
FileInputStream input = null;
try{
input = new FileInputStream("a.txt");
ByteArrayOutputStream output = new ByteArrayOutputStream();
int b;
while((b = input.read()) > 0) {
output.write(b);
}
byte[] byteArray = output.toByteArray();
System.out.println(new String(byteArray));
String content = output.toString();
System.out.println(content);
}catch(IOException e) {
e.printStackTrace();
}finally {
try{
if(input != null) {
input.close();
}
}catch(IOException e){
e.printStackTrace();
}
}