System.out closed? Can I reopen it?

前端 未结 7 2400
逝去的感伤
逝去的感伤 2020-12-06 09:34

I was helping a friend to write some Java code, who doesn\'t know a lot about Java. So I wrote him some helper functions to easily get things done that are a little quirky i

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 10:22

    Like the others have said, a stream should be closed where it was opened. However, you could write a facade to protect a stream from getting closed like this:

    import java.io.FilterOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    public class UnclosableOutputStream extends FilterOutputStream {
    
        public UnclosableOutputStream(OutputStream out) {
            super(out);
        }
    
        @Override
        public void close() throws IOException {
            out.flush();
        }
    }
    

    and use it like this:

    new StreamHelper().write("Hello Test", new UnclosableOutputStream(System.out));
    

    Might come in handy for test scenarios etc.

提交回复
热议问题