从一个OutputStream写入到另一个InputStream。

huangapple go评论82阅读模式
英文:

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!

huangapple
  • 本文由 发表于 2020年10月23日 03:02:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64488873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定