Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.