用Java复制文件的最快方法

Mat*_*ato 21 java file-io

什么是用Java复制大量文件的最快方法.到目前为止,我已经使用了文件流和nio.整体流似乎比nio快.到目前为止你有什么经历?

mih*_*ihn 21

http://www.baptiste-wicht.com/2010/08/file-copy-in-java-benchmark/可能会得到你的答案.

对于基准测试,我使用不同的文件进行了测试.

  1. 小文件(5 KB)
  2. 中等文件(50 KB)
  3. 大文件(5 MB)
  4. 胖文件(50 MB)
  5. 并且一个巨大的文件(1.3 GB)只有二进制文件

我首先使用文本文件然后使用二进制文件进行测试.我用三种模式进行了测试:

  1. 在同一个硬盘上.这是一个250 GB的IDE硬盘,带有8 MB的缓存.它的格式为Ext4.
  2. 两个磁盘之间.我使用了第一个磁盘和另一个250 GB的SATA硬盘和16 MB的缓存.它的格式为Ext4.
  3. 两个磁盘之间.我使用了第一个磁盘和另一个1 TB的SATA硬盘和32 MB的缓存.它使用NTFS格式化.

我使用了这里描述的基准框架来进行所有方法的测试.测试是在我的个人计算机上进行的(Ubuntu 10.04 64位,Intel Core 2 Duo 3.16 GHz,6 Go DDR2,SATA硬盘).使用的Java版本是Java 7 64位虚拟机...


Rom*_*eau 10

我会用:

import java.io.*;
import java.nio.channels.*;

public class FileUtils{
    public static void copyFile(File in, File out) 
        throws IOException 
    {
        FileChannel inChannel = new
            FileInputStream(in).getChannel();
        FileChannel outChannel = new
            FileOutputStream(out).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(),
                    outChannel);
        } 
        catch (IOException e) {
            throw e;
        }
        finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }

    public static void main(String args[]) throws IOException{
        FileUtils.copyFile(new File(args[0]),new File(args[1]));
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您的任何文件在Windows中大于64M,则可能需要查看以下内容:http: //forums.sun.com/thread.jspa?threadID = 4396.95&messageID = 2917510

  • catch(IOException e){throw e; } <---很好 (10认同)