Java 9 thêm readNBytes() vào InputStream. Đọc số byte yêu cầu từ input stream vào byte array. Block cho đến khi: đọc đủ len byte, hết stream, hoặc exception. Không đóng input stream. Hữu ích tránh vấn đề bộ nhớ với file lớn.
Cú pháp
public int readNBytes(byte[] b, int off, int len) throws IOException
Ví dụ: Đọc 7 byte đầu file
import java.io.*;
import java.util.stream.*;
import java.nio.*;
import java.nio.file.*;
public class InputStreamReadNByteMethodTest {
InputStream inputStream = InputStreamReadNByteMethodTest.class.getResourceAsStream("Technology.txt");
public void testReadNBytes() throws Exception {
final byte[] data = new byte[10];
inputStream.readNBytes(data, 0, 7);
System.out.println(new String(data));
}
public static void main(String args[]) throws Exception {
InputStreamReadNByteMethodTest t = new InputStreamReadNByteMethodTest();
t.testReadNBytes();
}
}
Kết quả (file Technology.txt chứa: "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA")
"JAVA",
readNBytes() vs read() vs readAllBytes()
| Phương thức | Trả về | Hành vi | Dùng khi |
|---|---|---|---|
read() | int (1 byte hoặc -1) | Đọc 1 byte, non-blocking nếu có data | Byte-by-byte processing |
read(byte[]) | int (số byte đọc được) | Đọc lên đến array length, có thể < len | Buffered read, loop |
readNBytes(byte[], off, len) | int (số byte thực đọc) | Block cho đến khi đủ len byte hoặc EOF | Cần chính xác N byte (header, fixed-format) |
readAllBytes() | byte[] | Đọc toàn bộ stream vào memory | File nhỏ, config, test data |
Lưu ý
readNBytesđảm bảo đọc đủlenbyte (trừ khi EOF) – khácread(byte[])có thể đọc ít hơn.- Không tự close stream – caller tự quản lý (try-with-resources).
- Phù hợp đọc header binary, fixed-size record, chunked processing file lớn.
readNBytes() lấp đầy khoảng trống giữa read() đơn giản và readAllBytes() tham lam bộ nhớ.