一、使用ByteArrayOutputStream
如果我們需要將OutputStream轉換為位元組數組,我們可以使用ByteArrayOutputStream。其實ByteArrayOutputStream底層就是用一個byte數組保存了所有的輸出位元組,當需要輸出時,直接從byte數組中取出位元組輸出即可。
下面是使用ByteArrayOutputStream將OutputStream轉換為位元組數組的示例代碼:
public byte[] toByteArray(OutputStream out) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = out.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
return bos.toByteArray();
}
二、使用PipedInputStream和PipedOutputStream
PipedInputStream和PipedOutputStream是一對管道流,可以讓一個線程將數據寫入PipedOutputStream,另一個線程從PipedInputStream讀取數據。我們可以將一個PipedOutputStream連接到一個PipedInputStream上,將數據寫入PipedOutputStream,再從PipedInputStream讀取數據,從而實現將OutputStream轉換為位元組數組。
下面是使用PipedInputStream和PipedOutputStream將OutputStream轉換為位元組數組的示例代碼:
public byte[] toByteArray(OutputStream out) throws IOException {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
new Thread(() -> {
try {
out.write(pos);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = pis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
return bos.toByteArray();
}
三、使用FileOutputStream和FileInputStream
我們也可以將OutputStream的輸出先寫入一個臨時文件中,然後再從文件中讀取位元組轉換為位元組數組。
下面是使用FileOutputStream和FileInputStream將OutputStream轉換為位元組數組的示例代碼:
public byte[] toByteArray(OutputStream out) throws IOException {
File tempFile = File.createTempFile("outputstream", "tmp");
FileOutputStream fos = new FileOutputStream(tempFile);
out.write(fos);
FileInputStream fis = new FileInputStream(tempFile);
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = fis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
return bos.toByteArray();
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/246841.html
微信掃一掃
支付寶掃一掃