2011-01-12 105 views
5

我有将文件复制到其他位置的代码。尝试复制大文件时出现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(); 
     } 
    } 

} 
} 

虽然复制小块,比如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密切合作。你能帮我解决吗?提前谢谢你。

+0

尝试使用Files.copy http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html如果它有效,请在src中查看 – oluies 2011-01-12 08:28:17

+0

谢谢。但我宁愿不在这个特定的情况下使用第三方库。 – 2011-01-12 08:29:54

回答

5

我想你可能已经碰到了前一段已经遇到的old bug。我没有试图复制一个文件,而是试图通过一个失败的内存映射文件。对我来说,解决方法是在循环中查找文件并请求GCfinalizers每隔一段时间运行一次。

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

+1

我找到了解决方案。感谢您的洞察力。 http://snippets.dzone.com/posts/show/4946 – 2011-01-12 09:11:27

2

您是内存映射文件,但是在32位JVM(我推测您正在使用)中存在有限的内存地址空间,因此映射方法失败。我不认为你可以映射超过1.3-1.4 GB的磁盘数据。您使用的堆大小是多少?

您可以尝试减少堆大小或使用64位JRE。或者,不要通过使用NIO将其映射到内存来读取文件。相反,使用缓冲读写器的传统方式来读取和写入一个文件中的数据。