繁体   English   中英

从文件中读取字节时出现 OutOfMemoryException

[英]OutOfMemoryException when reading bytes from file

我正在尝试制作一个十六进制转储应用程序,为此,我需要读取文件字节。 我正在使用 apache io 版本 2.8.0 进行十六进制转储。 这是我正在使用的代码:

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
                byte[] bytes = Files.readAllBytes(Paths.get(getPackageManager().getApplicationInfo("com.pixel.gun3d", 0).nativeLibraryDir.concat("/libil2cpp.so")));
                Log.e("MainActivity", dumpHex(bytes));
            } catch (PackageManager.NameNotFoundException | IOException e) {
                e.printStackTrace();
            }
        }

    private String dumpHex(byte[] bytes) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            HexDump.dump(bytes, 0, out, 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(out.toByteArray());
    }

我得到的错误是这样的: java.lang.OutOfMemoryError: Failed to allocate a 155189264 byte allocation with 25165824 free bytes and 94MB until OOM, max allowed footprint 328602112, growth limit 402653184我查了一下,没有任何建议在清单中添加android:largeHeap="true"android:hardwareAccelerated="false"即可。 任何帮助表示赞赏<3

读取文件时,建议将读取分区为小块以避免此类错误。 将整个文件字节读入字节数组是有限制的,例如文件大小超过 Integer.MAX_VALUE 你会得到一个 OutOfMemoryException。

尝试做类似的事情:


byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
int readBytesNum = fis.read(buffer);
while (readBytesNum > 0)
{
    //do what you need
    readBytesNum = in.read(buffer);
}

这意味着您需要更改 HexDump 的实现来处理分区中的文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM