ReadNBytes Caps Each Read At N Bytes
InputStream.readNBytes reads up to the requested count and never returns negative values, so chunked uploads get a clean empty-array end signal.
Code
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class ChunkReader {
public static void main(String[] args) throws IOException {
byte[] payload = "upload-chunk-boundary-demo".getBytes(StandardCharsets.UTF_8);
InputStream in = new ByteArrayInputStream(payload);
// readNBytes(len):最多读 len 字节;流提前结束时返回实际读到的量
byte[] chunk = in.readNBytes(10);
System.out.println("chunk: " + new String(chunk, StandardCharsets.UTF_8));
// 剩余不足 len:返回短数组而不是补零
byte[] tail = in.readNBytes(100);
System.out.println("tail length: " + tail.length);
// 再读一次:流耗尽后返回空数组,而不是 null
System.out.println("eof read: " + Arrays.toString(in.readNBytes(5)));
// readAllBytes 一次拿完剩余内容
System.out.println("all remaining: " + in.readAllBytes().length);
}
}A stepwise read of the file
All of the logic lives in the class ChunkReader.
Caveats
- No installation is required; the snippet works entirely with the standard library.
Applying it
The run emits 4 labeled sections — chunk:, tail length:, eof read:, all remaining: — one per step.
Statements that matter
byte[] payload = "upload-chunk-boundary-demo".getBytes(StandardCharsets.UTF_8);
InputStream in = new ByteArrayInputStream(payload);
byte[] chunk = in.readNBytes(10);
Interactive Tools for This Topic
FAQ
- What does ReadNBytes Caps Each Read At N Bytes print when run?
- No setup needed: run the file and look for labeled lines like `chunk:`, `tail length:`, `eof read:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.