Java中如何实现outputStream转inputStream呢?
下文笔者讲述outputStream转inputStream的方法及示例分享,如下所示
outputStream转inputStream的实现思路
方式1:
使用byte array进行相应的转换
方式2:
使用Pipes进行相应的转换
方式3:
使用Circular Buffers进行转换
例
使用byte array缓存转换
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
使用Pipes
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
new Thread(
new Runnable(){
public void run(){
class1.putDataOnOutputStream(out);
}
}
).start();
class2.processDataFromInputStream(in);
注意事项
PipedInputStream中存储数据的数组大小默认为1024
使用过程中不可扩充
当一次性写入的数据超过这个数
则会有个AssertionError抛出
当然,我们可以在初始化PipedInputStream的时候进行设置
上述代码仅为pipe的一种使用的方式,其也可以初始化如下
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
使用Circular Buffers
作为PipedInputStream和PipedOutputStream的一种替代方式
CircularBuffer有着更为简单的数据结构和使用方法
但是其并不是JDK自带的类需要额外引入
<!-- https://mvnrepository.com/artifact/org.ostermiller/utils -->
<dependency>
<groupId>org.ostermiller</groupId>
<artifactId>utils</artifactId>
<version>1.07.00</version>
</dependency>
CircularByteBuffer cbb = new CircularByteBuffer();
new Thread(
new Runnable(){
public void run(){
class1.putDataOnOutputStream(cbb.getOutputStream());
}
}
).start();
class2.processDataFromInputStream(cbb.getInputStream());
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


