← 中文资源

简体中文版本

readNBytes 每次读取不超过 N 字节

readNBytes 最多读取请求的字节数:流提前结束时返回短数组而不是补零,耗尽后返回空数组而不是 null,分块上传据此判断结束。Arrays.toString 直接打印 eof 空数组的内容,ByteArrayInputStream 让边界可复现。

阅读英文原文

实现说明

底层就是类 ChunkReader。

使用要点

  • 每一步打印都带着自己的标签:chunk:、tail length:、eof read:。

常见问题

运行「readNBytes 每次读取不超过 N 字节」会打印什么?

运行文件本身,chunk:、tail length:、eof read: 这些前缀各对应一段演示逻辑。

核心语句

byte[] payload = "upload-chunk-boundary-demo".getBytes(StandardCharsets.UTF_8);
InputStream in = new ByteArrayInputStream(payload);
byte[] chunk = in.readNBytes(10);

代码示例

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);
    }
}