Skip to content

Instantly share code, notes, and snippets.

@serba
Last active Oct 19, 2017
Embed
What would you like to do?
InputStream that fills a buffer and runs a callback
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterators;
import org.apache.commons.io.IOUtils;
public class Main {
public static void main(String[] args) throws Exception {
BufferingInputStreamFactory.Callback callback = buffer -> System.out.println(new String(buffer, StandardCharsets.UTF_8));
String string = "1234567890";
InputStream src = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
BufferingInputStreamFactory bis = new BufferingInputStreamFactory();
InputStream bufferingStream = bis.getBufferingStream(src, 2, callback);
IOUtils.read(bufferingStream, new byte[10]);
}
public static class BufferingInputStreamFactory {
public InputStream getBufferingStream(final InputStream src, final int bufferSize, final Callback callback) {
byte[] buffer = new byte[bufferSize];
Iterator<InputStream> iterator = new AbstractIterator<InputStream>() {
private boolean endOfStream = false;
@Override
protected InputStream computeNext() {
if (endOfStream) {
return endOfData();
}
try {
int size = IOUtils.read(src, buffer, 0, bufferSize);
if (size != bufferSize) {
endOfStream = true;
}
callback.processBuffer(buffer);
return new ByteArrayInputStream(buffer, 0, size);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
return new SequenceInputStream(Iterators.asEnumeration(iterator));
}
@FunctionalInterface
public interface Callback {
void processBuffer(byte[] buffer);
}
}
}
12
34
56
78
90
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment