Inputstream 转成outputstream
时间: 2023-06-07 16:11:04 浏览: 180
将一个InputStream转换成一个OutputStream可以通过使用java.io.PipedInputStream和java.io.PipedOutputStream实现。具体步骤如下:
1.创建一个PipedInputStream对象,它将接收从输入流读取的字节流。
2.创建一个PipedOutputStream对象,它将发送将要写入到输出流的字节流。
3.通过调用PipedInputStream对象的connect()方法将其连接到PipedOutputStream对象。
4.在另一个线程中,使用输入流读取字节并将它们写入到输出流中,这样就可以向输出流中写入字节。
代码示例:
```
InputStream input = ...; // 待转换的输入流
PipedInputStream pipedInput = new PipedInputStream();
PipedOutputStream pipedOutput = new PipedOutputStream();
// 将PipedInputStream和PipedOutputStream连接起来
pipedInput.connect(pipedOutput);
// 创建一个线程,用于读取输入流并将字节写入输出流
new Thread(() -> {
try {
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) >= 0) {
pipedOutput.write(buffer, 0, length);
}
} catch (IOException e) {
// 发生异常时,关闭管道
e.printStackTrace();
try {
pipedOutput.close();
} catch (IOException e1) { }
} finally {
// 关闭输入流
try {
input.close();
} catch (IOException e) { }
}
}).start();
```
阅读全文
相关推荐


















