2015-09-04 104 views
1

我試圖加密一個大文件,它是500MB,但是我的代碼引發了內存不足錯誤,對於小於50MB的小文件,代碼工作正常。我使用名爲JNCryptor的第三方庫進行加密,請查看我的代碼並糾正我是否有任何錯誤。提前致謝。編寫大文件時OutofMemory錯誤Android

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(); 
} 
+2

代替在密文中獲取完整內容,逐個讀取文件並追加到目標文件 – KOTIOS

+2

@sweeper不! CodeReview不是一個錯誤檢查服務 – Kaz

+0

這個庫(我不知道,我不使用)在api公共類中有一種輸入/輸出流,但沒有看到這樣的使用是可能的。像未完成的工作? –

回答

0

這是由JNCryptor來管理內存,特別是如果它使用臨時緩衝區。最好在流而不是緩衝區上工作。僅用於測試,如果直接將fileData寫入OutFile,是否會發生OutOfMemoryError?

writeFile(filedata, Outfile);