Created
April 23, 2019 00:57
-
-
Save juanplopes/b3b6a278f372f9b2b120270166306c80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.OutputStream; | |
public class LazyOutputStream<T extends OutputStream> extends OutputStream { | |
private final Factory<T> factory; | |
private T stream; | |
public LazyOutputStream(Factory<T> factory) { | |
this.factory = factory; | |
} | |
public T get() throws IOException { | |
return stream != null ? stream : (stream = factory.create()); | |
} | |
@Override | |
public void write(int b) throws IOException { | |
get().write(b); | |
} | |
@Override | |
public void write(@NotNull byte[] b) throws IOException { | |
get().write(b); | |
} | |
@Override | |
public void write(@NotNull byte[] b, int off, int len) throws IOException { | |
get().write(b, off, len); | |
} | |
@Override | |
public void flush() throws IOException { | |
get().flush(); | |
} | |
@Override | |
public void close() throws IOException { | |
get().close(); | |
} | |
public interface Factory<T extends OutputStream> { | |
T create() throws IOException; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment