Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created April 23, 2019 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanplopes/b3b6a278f372f9b2b120270166306c80 to your computer and use it in GitHub Desktop.
Save juanplopes/b3b6a278f372f9b2b120270166306c80 to your computer and use it in GitHub Desktop.
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