gpt4 book ai didi

java - 尝试复制大文件时 NIO 出错

转载 作者:搜寻专家 更新时间:2023-10-31 19:49:59 25 4
gpt4 key购买 nike

我有将文件复制到另一个位置的代码。

public static void copyFile(String sourceDest, String newDest) throws IOException {

File sourceFile = new File(sourceDest);
File destFile = new File(newDest);
if (!destFile.exists()) {
destFile.createNewFile();
}

FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}

}
}

在复制小块时,比如 300-400 Mb,一切都像变魔术一样有效。但是当我试图复制一个大小为 1.5 Gb 的文件时,它失败了。堆栈是:

run: 12.01.2011 11:16:36 FileCopier main SEVERE: Exception occured while copying file. Try again. java.io.IOException: Map failed at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:748) at sun.nio.ch.FileChannelImpl.transferFromFileChannel(FileChannelImpl.java:527) at sun.nio.ch.FileChannelImpl.transferFrom(FileChannelImpl.java:590) at FileCopier.copyFile(FileCopier.java:64) at FileCopier.main(FileCopier.java:27) Caused by: java.lang.OutOfMemoryError: Map failed at sun.nio.ch.FileChannelImpl.map0(Native Method) at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:745) ... 4 more BUILD SUCCESSFUL (total time: 0 seconds)

我没有与 NIO 密切合作。你能帮帮我吗?非常感谢您。

最佳答案

我想你可能被 old bug 击中了前段时间已经遇到过。我不是要复制文件,而是要查找同样失败的内存映射文件。对我来说,解决方法是循环查找文件并请求 GCfinalizers时不时地跑。

内存映射的 ByteBuffers 在终结器中释放它们的映射,并为新的映射腾出空间。这非常丑陋,但至少它有效。我们希望他们在即将到来的 NIO 迭代中对此有所作为。

关于java - 尝试复制大文件时 NIO 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4666616/

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