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; }
InputStream?Stream<byte[]>? How are you planning on processing it?Stream, you need to connect theInputStreamto the client'sOutputStream, and just stream bytes normally. How this is done specifically depends on your environment, but for example with Spring you could use aStreamingResponseBody.InputStreamto the client, then any additionalFluxorbyte[]in between is completely unnecessary. It's just normal basic streaming. See here for more info.