如何在不将整个字节数组分配到内存的情况下编写文件?

问题描述 投票:1回答:5

我知道这是一个新手问题。你们能帮忙吗?

我说的是大文件,当然,超过100MB。我想象某种循环,但我不知道该用什么。分块流?

一个是肯定的:我不想要这样的东西(伪代码):

File file = new File(existing_file_path);
byte[] theWholeFile = new byte[file.length()]; //this allocates the whole thing into memory

File out = new File(new_file_path);
out.write(theWholeFile);

更具体地说,我必须重新编写一个下载base64编码文件并将其解码为“普通”文件的applet。因为它是由字节数组构成的,所以它在内存中保存两倍的文件大小:一个base64编码,另一个解码。我的问题不是关于base64。这是关于节省记忆。

你能为我指出正确的方向吗?谢谢!

java performance file memory
5个回答
4
投票

从问题来看,您似乎正在将文件的base64编码内容读入数组,在最终保存之前将其解码为另一个数组。

考虑内存时,这是一个开销。特别是考虑到Base64编码正在使用的事实。它可以通过以下方式提高效率:

完成读写操作的缓冲以防止频繁的IO访问。您可以使用适合您的应用程序负载的缓冲区大小;通常,缓冲区大小选择为some power of two, because such a number does not have an "impedance mismatch" with the physical disk buffer


2
投票

也许是文件上的FileInputStream,读取固定长度的块,进行转换并将它们写入FileOutputStream



0
投票

使用this base64 encoder/decoder,它将包装您的文件输入流并动态处理解码:

InputStream input = new Base64.InputStream(new FileInputStream("in.txt"));
OutputStream output = new FileOutputStream("out.txt");

try {
    byte[] buffer = new byte[1024];
    int readOffset = 0;
    while(input.available() > 0) {
        int bytesRead = input.read(buffer, readOffset, buffer.length);
        readOffset += bytesRead;
        output.write(buffer, 0, bytesRead);
    }
} finally {
    input.close();
    output.close();
}

0
投票

你可以使用org.apache.commons.io.FileUtils。除了您要查找的内容之外,此util类还提供其他选项。例如:

  • FileUtils.copyFile(final File srcFile, final File destFile)
  • FileUtils.copyFile(final File input, final OutputStream output)
  • FileUtils.copyFileToDirectory(final File srcFile, final File destDir)

等等..你也可以关注this tut.

© www.soinside.com 2019 - 2024. All rights reserved.