一、使用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/n/246841.html
微信扫一扫
支付宝扫一扫