【发布时间】:2019-06-25 10:45:11
【问题描述】:
我需要将大文件 (GB) 复制到另一个文件(容器)中,我想知道性能和内存使用情况。
像下面这样读取整个源文件:
RandomAccessFile f = new RandomAccessFile(origin, "r");
originalBytes = new byte[(int) f.length()];
f.readFully(originalBytes);
然后,像这样将所有内容复制到容器中:
RandomAccessFile f2 = new RandomAccessFile(dest, "wr");
f2.seek(offset);
f2.write(originalBytes, 0, (int) originalBytes.length);
一切都在内存中,对吗?那么复制大文件会影响内存并导致 OutOfMemory 异常?
按字节而不是完全读取原始文件是否更好? 在那种情况下,我应该如何进行? 提前谢谢你。
编辑:
按照mehdi maick的回答,我终于找到了解决方案: 我可以根据需要使用 RandomAccessFile 作为目标,并且因为 RandomAccessFile 有一个返回 FileChannel 的方法“getChannel”,我可以将其传递给以下方法,该方法将执行文件在我想要的目的地的位置:
public static void copyFile(File sourceFile, FileChannel destination, int position) throws IOException {
FileChannel source = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination.position(position);
int currentPosition=0;
while (currentPosition < sourceFile.length())
currentPosition += source.transferTo(currentPosition, 32768, destination);
} finally {
if (source != null) {
source.close();
}
}
}
【问题讨论】:
-
为什么不使用字节缓冲区,并以块的形式读取原始文件?性能方面很棒。
-
读入块/块,例如一次 64k,使用
FileInputStream和FileOutputStream -
@AlexandarPetrov 考虑到目标文件必须用 RandomAccessFile 编写,您能否提供一个示例?谢谢。
-
@Andreas 对你也一样;)
-
为什么目标文件必须写成
RandomAccessFile?您不是简单地将现有文件连接成一个组合文件吗?
标签: java randomaccessfile