public class Main {
public static void main(String[] args) {
byte[] content = null;
try {
content = Files.readAllBytes(Paths.get("/path/to/file.ext"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
Exception in thread "main" java.lang.OutOfMemoryError: Required array size too large
at java.nio.file.Files.readAllBytes(Unknown Source)
at Main.main(Main.java:13)
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以毫无例外地读取数组(流等)?该文件小于允许的 HEAP,因此应该可以在程序中一次存储所有数据。