简体   繁体   English

编写大文件Android时出现OutofMemory错误

[英]OutofMemory error while writing a large file Android

I'm trying to encrypt a large file which is 500MB but my code throws an out of memory error, for small files below 50MB the code works fine. 我正在尝试加密500MB的大文件,但是我的代码抛出了内存不足错误,对于50MB以下的小文件,代码可以正常工作。 Im using a third party library called JNCryptor for encryption, please have a look at my code and correct me if any mistake. 我正在使用名为JNCryptor的第三方库进行加密,请查看我的代码,如果有任何错误,请纠正我。 Thanks in advance. 提前致谢。

public void encrypt() {
    String file = Environment.getExternalStorageDirectory() + "/sai/ravi_enc.exe";
    byte[] filedata = null;
    try {
        filedata = IOUtils.toByteArray(new FileInputStream(file));
    } catch (IOException e) {
        e.printStackTrace();
    }

    JNCryptor cryptor = new AES256JNCryptor();
    String password = "123456789";

    try {
        byte[] ciphertext = cryptor.decryptData(filedata, password.toCharArray());
        String Outfile = Environment.getExternalStorageDirectory() + "/sai/ravi_dec.exe";
        writeFile(ciphertext, Outfile);
        System.out.println("Done");
    } catch (CryptorException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void writeFile(byte[] data, String fileName) throws IOException {
    FileOutputStream out = new FileOutputStream(fileName);
    out.write(data);
    out.close();
}

This is up to JNCryptor to well manage memory, especially if it uses temp buffer. 这取决于JNCryptor能否很好地管理内存,尤其是在使用临时缓冲区的情况下。 It is better to work on streams instead of buffers. 最好处理流而不是缓冲区。 Just for testing, if you write directly the fileData to your outFile, do you get OutOfMemoryError? 仅出于测试目的,如果直接将fileData写入outFile,会得到OutOfMemoryError吗?

writeFile(filedata, Outfile);

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

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