Skip to content

Instantly share code, notes, and snippets.

@zikani03
Last active July 17, 2022 15:31
Show Gist options
  • Save zikani03/27bdfd08e2c67eb9f5097542c44690eb to your computer and use it in GitHub Desktop.
Save zikani03/27bdfd08e2c67eb9f5097542c44690eb to your computer and use it in GitHub Desktop.
Writing to multiple output streams in Java
import java.io.IOException;
import java.io.OutputStream;
/**
* <p>
* MultiplexOutputStream allows you to write to multiple output streams "at once".
* It allows you to use one outputstream writer to write to multiple outputstreams
* without repeating yourself.
* Based off <a href="https://github.com/creditdatamw/kapenta/blob/master/src/main/java/com/creditdatamw/labs/kapenta/io/MultiplexOutputStream.java">MultiplexOutputStream.java</a>
*/
public class MultiplexOutputStream extends OutputStream {
private OutputStream[] outputStreams;
public MultiplexOutputStream(OutputStream... outputStreams) {
java.util.Objects.requireNonNull(outputStreams);
assert(outputStreams.length > 0);
for(Object o: outputStreams) {
java.util.Objects.requireNonNull(o);
}
this.outputStreams = outputStreams;
}
@Override
public void write(int b) throws IOException {
for(OutputStream os: outputStreams) {
os.write(b);
}
}
@Override
public void write(byte[] b) throws IOException {
for(OutputStream os: outputStreams) {
os.write(b);
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
for(OutputStream os: outputStreams) {
os.write(b, off, len);
}
}
@Override
public void flush() throws IOException {
for(OutputStream os: outputStreams) {
os.flush();
}
}
@Override
public void close() throws IOException {
for(OutputStream os: outputStreams) {
os.close();
}
}
}
public class MultiplexOutputStreamExample {
public static void main(String... args) {
File file1 = new File("output-1.txt");
File file2 = new File("/tmp/backup/output-2.txt");
try (FileOutputStream fos1 = new FileOutputStream(file1);
FileOutputStream fos2 = new FileOutputStream(file2);
MultiplexOutputStream mos = new MultiplexOutputStream(fos1, fos2)) {
Files.copy(Paths.get("input.txt"), mos);
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
@ShashankShane
Copy link

Yejbx jfjnd
Bdjdjn
Bdndn

@ShashankShane
Copy link

Hsjdjf

@ShashankShane
Copy link

Dnjdkfk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment