Scala,输出到多个文件/流

时间:2013-06-07 13:46:50

标签: scala

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

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

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中的库中实现?

1 个答案:

答案 0 :(得分: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负责所有格式化业务,而您只需重定向数据。