Skip to content

Instantly share code, notes, and snippets.

@zikani03
Last active September 19, 2024 14:04
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

Hsjdjf

@ShashankShane
Copy link

Dnjdkfk

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