Reputation: 1097
As I understand, an InputStream
is a stream of bytes. I am interested in converting an InputStream object to a stream of bytes. Basically, an implementation of the following method.
public Stream<byte[]> toStream(final InputStream is, final int bufferSize);
What would be the best way to get this done? The buffer size is the number of bytes read from the InputStream at a time.
Upvotes: 2
Views: 353
Reputation: 159086
You need to write your own Spliterator
, something like this:
public final class ChunkingInputStreamSpliterator implements Spliterator<byte[]> {
private final InputStream is;
private final int bufferSize;
public ChunkingInputStreamSpliterator(InputStream is, int bufferSize) {
this.is = is;
this.bufferSize = bufferSize;
}
@Override
public boolean tryAdvance(Consumer<? super byte[]> action) {
byte[] bytes;
try {
bytes = this.is.readNBytes(this.bufferSize);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (bytes.length == 0)
return false;
action.accept(bytes);
return true;
}
@Override
public Spliterator<byte[]> trySplit() {
return null; // cannot split an InputStream
}
@Override
public long estimateSize() {
return Long.MAX_VALUE; // unknown
}
@Override
public int characteristics() {
return Spliterator.ORDERED | Spliterator.NONNULL;
}
}
Then implement your method like this:
public static Stream<byte[]> toStream(InputStream is, int bufferSize) {
return StreamSupport.stream(new ChunkingInputStreamSpliterator(is, bufferSize), false);
}
If you don't have Java 11, so you don't have the very convenient readNBytes
method, then do that part yourself like this:
public boolean tryAdvance(Consumer<? super byte[]> action) {
byte[] bytes = new byte[this.bufferSize];
int len = 0;
try {
for (int read; len < bytes.length; len += read)
if ((read = this.is.read(bytes, len, bytes.length - len)) <= 0)
break;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (len == 0)
return false;
if (len < bytes.length)
bytes = Arrays.copyOfRange(bytes, 0, len);
action.accept(bytes);
return true;
}
Upvotes: 2