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

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

Write from one OutputStream to another InputStream

问题

我想在一个类中拥有一个类似这样的InputStream

  1. class A {
  2. InputStream inputStream = ...
  3. }

然后,我想使用另一个在同一应用程序中的类中的OutputStream向该InputStream写入。这种做法可行吗?

英文:

I want to have an InputStream in a class like this:

  1. class A {
  2. InputStream inputStream = ...
  3. }

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参见)。

以下是一个简单的示例,演示如何使用它:

  1. public static void main(String[] args) throws ParseException, IOException {
  2. PipedInputStream inputStream = new PipedInputStream();
  3. PipedOutputStream outputStream = new PipedOutputStream(inputStream);
  4. // 向输出流写入一些数据
  5. writeDataToOutputStream(outputStream);
  6. // 现在读取那些数据
  7. Scanner src = new Scanner(inputStream);
  8. System.out.println(src.nextLine());
  9. }
  10. private static void writeDataToOutputStream(OutputStream outputStream) throws IOException {
  11. outputStream.write("Hello!\n".getBytes());
  12. }

这段代码将输出:

  1. Hello!
英文:

Yes it is! PipedOutputStream (see) and a PipedInputStream (see) is what you need.

Here is a little example how to use it:

  1. public static void main(String[] args) throws ParseException, IOException {
  2. PipedInputStream inputStream = new PipedInputStream();
  3. PipedOutputStream outputStream = new PipedOutputStream(inputStream);
  4. // Write some data to the output stream
  5. writeDataToOutputStream(outputStream);
  6. // Now read that data
  7. Scanner src = new Scanner(inputStream);
  8. System.out.println(src.nextLine());
  9. }
  10. private static void writeDataToOutputStream(OutputStream outputStream) throws IOException {
  11. outputStream.write("Hello!\n".getBytes());
  12. }

The code will output:

  1. 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:

确定