0

我需要将相同的文本写入多个文件(或流)。有时我需要使用 Writer,有时是 PrintWriter,有时是 OutputStream...

在 Java 中执行此操作的一种方法是将 PrintWriter 扩展为具有 PrintWriter 数组并覆盖每个方法,如下所示:

class MutiplePrintWriter extends PrintWriter {
    private PrintWriter[] outs;
    public MutiplePrintWriter(PrintWriter[] outs) { this.out = out; }

    public void print(boolean b) { for (PrintWriter out : outs) print(b); }
    public void print(char c) { for (PrintWriter out : outs) print(c); }
    public void print(char[] s) { for (PrintWriter out : outs) print(s); }
    ...
}   

(对于 Writer、OutputStream 也是一样的......)

Scala中有更好的选择吗?

这是否已经在 Scala 的库中实现?

4

1 回答 1

1

我可以在 Java 世界中回答您的问题:在级别上实现您的多编写器类OutputStream,然后在顶部堆叠一个Writer/ :PrintWriter

class MultiOutputStream(val outs: Array[OutputStream]) extends OutputStream {
  override def close() = {
    super.close()
    outs.foreach(_.close)
  }
  override def flush() = {
    super.flush()
    outs.foreach(_.flush)
  }
  def write(c: Int) = outs.foreach(_.write(c))

  // overridden for efficiency
  override def write(b: Array[Byte], off: Int, len: Int) = 
    outs.foreach(_.write(b,off,len))
}

现在创建你需要的任何东西:

val outs = //...
val out = new PrintStream(new MultiOutputStream(outs))

这样,PrintStream您只需重定向数据即可处理所有格式化业务。

于 2013-06-07T15:25:19.680 回答