How to write data to two java.io.OutputStream objects at once?

前端 未结 5 917
野性不改
野性不改 2020-11-27 20:37

I\'m looking for magical Java class that will allow me to do something like this:

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
FileOutputS         


        
5条回答
  •  一向
    一向 (楼主)
    2020-11-27 21:10

    Just found this thread beacause I had to face the same problem. If someone wants to see my solution (java7 code):

    package Core;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    
    public class MultiOutputStream extends OutputStream {
    
    private List out;
    
    public MultiOutputStream(List outStreams) {
    
        this.out = new LinkedList();
    
        for (Iterator i = outStreams.iterator(); i.hasNext();) {
            OutputStream outputStream = (OutputStream) i.next();
    
            if(outputStream == null){
                throw new NullPointerException();
            }
            this.out.add(outputStream);
        }
    }
    
    @Override
    public void write(int arg0) throws IOException {
    
        for (Iterator i = out.iterator(); i.hasNext();) {
            OutputStream var = (OutputStream) i.next();
    
            var.write(arg0);
        }
    }
    
    @Override
    public void write(byte[] b) throws IOException{
    
        for (Iterator i = out.iterator(); i.hasNext();) {
            OutputStream var = (OutputStream) i.next();
    
            var.write(b);
        }
    }
    
    @Override
    public void write(byte[] b, int off, int len) throws IOException{
    
        for (Iterator i = out.iterator(); i.hasNext();) {
            OutputStream var = (OutputStream) i.next();
    
            var.write(b, off, len);
        }
    }
    
    @Override
    public void close() throws IOException{
    
        for (Iterator i = out.iterator(); i.hasNext();) {
            OutputStream var = (OutputStream) i.next();
    
            var.close();
        }
    }
    
    @Override
    public void flush() throws IOException{
    
        for (Iterator i = out.iterator(); i.hasNext();) {
            OutputStream var = (OutputStream) i.next();
    
            var.flush();
        }
    }
    
    }
    

    Works fine so far, just tested some basic operation, e.g. setting up a MultiOutputStream from the System.out Stream and 2 PrintStreams each writing into a seperate log. I used

    System.setOut(multiOutputStream);
    

    to write to my terminal screen and two logs which worked without any problems.

提交回复
热议问题