如何一次将数据写入两个java.io.OutputStream对象?

2022-09-01 02:28:17

我正在寻找神奇的Java类,它将允许我做这样的事情:

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
FileOutputStream fileStream = new FileOutputStream(new File("/tmp/somefile"));

MultiOutputStream outStream = new MultiOutputStream(byteStream, fileStream);

outStream.write("Hello world".getBytes());

基本上,我想要Java中的s。有什么想法吗?teeOutputStream

谢谢!


答案 1

答案 2

只需自己滚动即可。根本没有任何魔力。使用Apache的TeeOutputStream,你基本上会使用下面的代码。当然,使用Apache Commons I / O库,您可以利用其他类,但有时实际上为自己编写一些东西是很好的。:)

public final class TeeOutputStream extends OutputStream {

  private final OutputStream out;
  private final OutputStream tee;

  public TeeOutputStream(OutputStream out, OutputStream tee) {
    if (out == null)
      throw new NullPointerException();
    else if (tee == null)
      throw new NullPointerException();

    this.out = out;
    this.tee = tee;
  }

  @Override
  public void write(int b) throws IOException {
    out.write(b);
    tee.write(b);
  }

  @Override
  public void write(byte[] b) throws IOException {
    out.write(b);
    tee.write(b);
  }

  @Override
  public void write(byte[] b, int off, int len) throws IOException {
    out.write(b, off, len);
    tee.write(b, off, len);
  }

  @Override
  public void flush() throws IOException {
    out.flush();
    tee.flush();
  }

  @Override
  public void close() throws IOException {
    try {
      out.close();
    } finally {
      tee.close();
    }
  }
}

使用上述类进行测试,如下所示

public static void main(String[] args) throws IOException {
  TeeOutputStream out = new TeeOutputStream(System.out, System.out);
  out.write("Hello world!".getBytes());
  out.flush();
  out.close();
}

会打印.Hello World!Hello World!

(注意:被覆盖的可以使用一些小心:)close()


推荐