小编Nit*_*ton的帖子

Java - 读取大文件(几 GB)


这个问题很短。我有一个大小为 4GB 的文件,目前我确实使用以下代码读取了它:
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,因此应该可以在程序中一次存储所有数据。

java out-of-memory file-read java-stream

-6
推荐指数
1
解决办法
3391
查看次数

标签 统计

file-read ×1

java ×1

java-stream ×1

out-of-memory ×1