gpt4 book ai didi

java加密大文件导致java.lang.OutOfMemoryError : Java heap space,可能的解决方案

转载 作者:行者123 更新时间:2023-12-01 07:47:44 24 4
gpt4 key购买 nike

我正在编写java程序来加密视频文件,对于小视频文件,它会按预期执行,但是当我尝试处理大约800兆字节的大文件时,它会抛出异常java.lang.OutOfMemoryError:Java 堆空间。我研究了这个主题,从 here 获取有关垃圾收集器的更多信息。并审查类似问题here 。根据最佳选择的答案,如何“一次加密一个字节”:使用 block 密码加密是按 block (AES:16字节)进行的。我的源代码的内容

main.java

public static void main(String[] args) {
String key = "Mary has one cat";
File inputFile = new File("C:\\Users\\xyz\\Music\\test\\-.mp4");
File encryptedFile = new File("C:\\Users\\xyz\\Music\\test\\-.mp4.encrypted");
File decryptedFile = new File("C:\\Users\\xyz\\Music\\test\\decrypted.mp4");

try {
CryptoUtils.encrypt(key, inputFile, encryptedFile);
CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
} catch (CryptoException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}

CryptoUtils.java

 private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES";

public static void encrypt(String key, File inputFile, File outputFile)
throws CryptoException {
doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
}

public static void decrypt(String key, File inputFile, File outputFile)
throws CryptoException {
doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
}

private static void doCrypto(int cipherMode, String key, File inputFile,
File outputFile) throws CryptoException {
try {
Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(cipherMode, secretKey);

FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);

byte[] outputBytes = cipher.doFinal(inputBytes);

FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);

inputStream.close();
outputStream.close();

} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
}
}

CryptoException.java

public class CryptoException extends Exception {

public CryptoException() {
}

public CryptoException(String message, Throwable throwable) {
super(message, throwable);
}}

最佳答案

我认为您应该考虑使用 CipherOutputStream。这样您就不需要将文件加载到内存中:

https://docs.oracle.com/javase/9/docs/api/javax/crypto/CipherOutputStream.html

关于java加密大文件导致java.lang.OutOfMemoryError : Java heap space,可能的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48109791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com