英文:
Write from one OutputStream to another InputStream
问题
我想在一个类中拥有一个类似这样的InputStream
:
class A {
InputStream inputStream = ...
}
然后,我想使用另一个在同一应用程序中的类中的OutputStream
向该InputStream
写入。这种做法可行吗?
英文:
I want to have an InputStream
in a class like this:
class A {
InputStream inputStream = ...
}
And I want to write to that InputStream
using a OutputStream
from another class which is in the same application. Is it possible to do this?
答案1
得分: 1
是的,就是这样!你需要使用 PipedOutputStream
(参见)和 PipedInputStream
(参见)。
以下是一个简单的示例,演示如何使用它:
public static void main(String[] args) throws ParseException, IOException {
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream(inputStream);
// 向输出流写入一些数据
writeDataToOutputStream(outputStream);
// 现在读取那些数据
Scanner src = new Scanner(inputStream);
System.out.println(src.nextLine());
}
private static void writeDataToOutputStream(OutputStream outputStream) throws IOException {
outputStream.write("Hello!\n".getBytes());
}
这段代码将输出:
Hello!
英文:
Yes it is! PipedOutputStream
(see) and a PipedInputStream
(see) is what you need.
Here is a little example how to use it:
public static void main(String[] args) throws ParseException, IOException {
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream(inputStream);
// Write some data to the output stream
writeDataToOutputStream(outputStream);
// Now read that data
Scanner src = new Scanner(inputStream);
System.out.println(src.nextLine());
}
private static void writeDataToOutputStream(OutputStream outputStream) throws IOException {
outputStream.write("Hello!\n".getBytes());
}
The code will output:
Hello!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论