FileChannel.transferTo for large file in windows

前端 未结 3 1516
南方客
南方客 2021-01-31 23:20

Using Java NIO use can copy file faster. I found two kind of method mainly over internet to do this job.

public static void copyFile(File sourceFile, File destina         


        
相关标签:
3条回答
  • 2021-01-31 23:41

    There appears to be anecdotal evidence that attempts to transfer more than 64MB at a time on certain Windows versions results in a slow copy. Hence the check: this appears to be the result of some detail of the underlying native code that implements the transferTo operation on Windows.

    0 讨论(0)
  • 2021-01-31 23:56

    I have read that it is for compatibility with the Windows 2000 operating system.

    Source: http://www.rgagnon.com/javadetails/java-0064.html

    Quote: In win2000, the transferTo() does not transfer files > than 2^31-1 bytes. it throws an exception of "java.io.IOException: Insufficient system resources exist to complete the requested service is thrown." The workaround is to copy in a loop 64Mb each time until there is no more data.

    0 讨论(0)
  • 2021-02-01 00:01

    Windows has a hard limit on the maximum transfer size, and if you exceed it you get a runtime exception. So you need to tune. The second version you give is superior because it doesn't assume the file was transferred completely with one transferTo() call, which agrees with the Javadoc.

    Setting the transfer size more than about 1MB is pretty pointless anyway.

    EDIT Your second version has a flaw. You should decrement size by the amount transferred each time. It should be more like:

    while (position < size) {
        long count = inChannel.transferTo(position, size, outChannel);
        if (count > 0)
        {
            position += count;
            size-= count;
        }
    }
    
    0 讨论(0)
提交回复
热议问题