尝试复制大文件时NIO出错

Ant*_* K. 5 java nio

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

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();
        }
    }

}
}
Run Code Online (Sandbox Code Playgroud)

虽然复制小块,比如300-400 Mb,但一切都像魔术一样.但是,当我尝试复制1.5 Gb大小的文件时,它失败了.堆栈是:

run:12.01.2011 11:16:36 FileCopier main SEVERE:复制文件时发生异常.再试一次.java.io.IOException:在sun.nio.ch.FileChannelImpl的sun.nio.ch.FileChannelImpl.transferFromFileChannel(FileChannelImpl.java:527)的sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:748)上映射失败.transferFrom(FileChannelImpl.java:590)FileCopier.copyFile(FileCopier.java:64)at FileCopier.main(FileCopier.java:27)引起:java.lang.OutOfMemoryError:地图在sun.nio.ch.FileChannelImpl失败sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:745)的.map0(Native方法)... 4更多BUILD SUCCESSFUL(总时间:0秒)

我没有和NIO密切合作过.你能帮帮我吗?非常感谢你提前.

Wal*_*inz 5

我想你可能已经遇到过一段时间以前已经遇到的旧bug了.我没有尝试复制文件,而是寻找通过内存映射的文件,该文件也失败了.对我来说,解决方法是在循环中查找文件并请求GC终结器不时地运行.

内存ByteBuffers映射在终结器中释放它们的映射并为新映射腾出空间.这非常难看,但至少它有效.让我们希望他们在即将到来的NIO迭代中对此做些什么.