JavaUser Code: Multiplexing Output Streams

User Code: Multiplexing Output Streams content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Sometimes I needed to send the same data to several output streams. The most trivial
example is logging the data written to an output stream for debugging purpose.
I thought it useful to have a class that allows me to do this job. Since the
whole hierarchy of streams relys heavily on the decorator model, I decided to
use a similar approach.

The class MultiplexOutputStream obtained is used as all other streams in Java.
The following code exemplifies the usage by logging the data written to an output
stream to the standard error stream and to a file, too.

MultiplexOutputStream mos = new MultiplexOutputStream (os); // The decorated output stream
mos.addOutputStream (System.err);
mos.addOutputStream (new FileOutputStream (“Multiplex.log”));

PrintStream ps = new PrintStream (mos, true);
ps.println (“This is a test !”);


Download source = 1 Kb

About the Author

Bogdan Matasaru is a Romanian
working toward a Ph.D. in Austria, with a dissertation on systolic algorithms for
multiprecision rational arithmetic. Bogdan has worked as a programmer in various fields.
Bogdan’s latest projects have involved me satellite communication (and some ugly interfaces
with on-board units for vehicles). Part of Bogdan’s Ph.D. work concerns a multiprecision
arithmetic library for Java, usable for taking advantage of different computer
architectures: multiprocessor computers, FPGA coprocessors, and so on.

[To contribute a code article to Gamelan, please contact]

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories