问题描述
我用小于这个(10mb、100mb、500mb)的文件测试了我的代码并且加密有效.但是,我遇到了大于 1gb 的文件的问题.我生成了一个大文件(大约 2gb),我想使用 JAVA 用 AES 对其进行加密,但我遇到了这个错误:
I've tested my code with files less than this(10mb, 100mb, 500mb) and the encryption works. However, I run in to problems with files greater than 1gb.I've generated a large file (about 2gb) and I want to encrypt it with AES using JAVA, but I'm running into this error:
线程main"中的异常java.lang.OutOfMemoryError:Java堆空间"
"Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"
我尝试过使用 -Xmx8G 来增加可用内存,但没有使用骰子.我的部分代码如下
I've tried increasing available memory by using -Xmx8G, but no dice.Part of my code is as follows
File selectedFile = new File("Z:\dummy.txt");
Path path = Paths.get(selectedFile.getAbsolutePath());
byte[] toencrypt = Files.readAllBytes(path);
byte[] ciphertext = aesCipherForEncryption.doFinal(toencrypt);
FileOutputStream fos = new FileOutputStream(selectedFile.getAbsolutePath());
fos.write(ciphertext);
fos.close();
据我所知,它之所以出现这种行为,是因为它试图一次读取整个文件,对其进行加密,然后将其存储到另一个字节数组中,而不是进行缓冲和流式传输.可以有人帮我提供一些代码提示吗?
As far as I can tell, the reason it is behaving this way, is that it is trying to read the whole file at once, encipher it, and store it into another byte array instead of buffering and streaming it in. Can anyone help me with some code tips?
我是编码初学者,所以我不太了解,任何帮助将不胜感激.
I am a beginner to coding, so I don't really know much, any help will be appreciated.
推荐答案
甚至不要尝试将整个大文件读入内存.一次加密一个缓冲区.只需使用包裹在 FileOutputStream
周围的适当初始化的 CipherOutputStream
执行标准复制循环即可.您可以将其用于所有文件,无需对其进行特殊处理.使用 8k 或更大的缓冲区.
Don't even try to read entire large files into memory. Encrypt a buffer at a time. Just do the standard copy loop with a suitably initialized CipherOutputStream
wrapped around the FileOutputStream
. You can use this for all files, no need to make a special case out of it. Use a buffer of 8k or more.
EDIT Java 中的标准复制循环"如下:
EDIT The 'standard copy loop' in Java is as follows:
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
在这种情况下 out = new CipherOutputStream(new FileOutputStream(selectedFile), cipher)
.
这篇关于使用 JAVA 使用 AES 加密大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!