0

I need to write the same text to multiple files (or streams). Sometimes I need to use Writer, sometimes a PrintWriter, sometimes a OutputStream...

One way to do this in Java wold be to extend a PrintWriter to have an array of PrintWriters and overridde each method as follows:

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); }
    ...
}   

(and the same for Writer, OutputStream...)

Is there a better alternative in Scala?

Is this already implemented in a library in Scala?

1 Answer 1

1

I can answer your question in the java-world: Implement your multi-writer class on OutputStream level and then stack a Writer/PrintWriter on top:

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))
}

Now create out of this whatever you need:

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

This way, the PrintStream takes care of all the formatting business, while you only have to redirect data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.