Java中如何将outputstream转化为inputStream
时间: 2024-04-10 14:26:51 浏览: 87
Java中IO解读与使用实例-动力节点共17页.pdf
在Java中,你可以使用PipedInputStream和PipedOutputStream来实现将OutputStream转化为InputStream。下面是一个示例代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class StreamConversionExample {
public static void main(String[] args) {
try {
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream(inputStream);
// 启动两个线程,一个写入数据到OutputStream,另一个从InputStream读取数据
Thread writerThread = new Thread(() -> {
try {
outputStream.write("Hello, World!".getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
});
Thread readerThread = new Thread(() -> {
try {
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
});
writerThread.start();
readerThread.start();
writerThread.join();
readerThread.join();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用了PipedInputStream和PipedOutputStream来实现将OutputStream转换为InputStream。通过PipedOutputStream写入数据到OutputStream,然后通过PipedInputStream从InputStream读取数据。这样就实现了将OutputStream转化为InputStream的功能。
阅读全文