java NIO复制文件总结 最快的两种方法

2 篇文章 0 订阅
1 篇文章 0 订阅

普通复制方法就不总结。

第一种:FileChanel.transferTo(0, size, out)

第二种:Files.copy(source, out)

两种都是NIO包下类。

第一种使用方法:

	public static void test3(){
		//输出7366ms
		long start = System.currentTimeMillis();
		System.out.println("writeBuffer-开始时间:"+start);
		FileChannel fci = null;
		FileChannel fco = null;
		try {
			fci = new RandomAccessFile("D:\\Eclipse\\workspace\\sdutent\\file1.txt", "rw").getChannel();
			fco = new RandomAccessFile("‪fileX.txt", "rw").getChannel();
			fci.transferTo(0, fci.size(), fco);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(fci!=null) {
					fci.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if(fco!=null) {
					fco.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("总消耗:"+(end-start));
	}

第二种使用方法:

	public static void test2() throws IOException {
		long start = System.currentTimeMillis();
		System.out.println("writeBuffer-开始时间:"+start);
		Files.copy(new File("D:\\Eclipse\\workspace\\sdutent\\file1.txt").toPath(), new FileOutputStream("‪fileX.txt"));
		long end = System.currentTimeMillis();
		System.out.println("总消耗:"+(end-start));
	}

两种方法在单线程下效率差不多。都是利用了NIO种的新特性--通道。

但是第一种方法更灵活,第二种比较简单。

FileChannel是线程安全的,所以可以利用多线程来进行复制文件,比如将文件分成4块,然后起4个线程去操作,这样效率提升的更明显。

PS:Files类是Java7之后推出来的,对文件的操作功能非常牛,建议多学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值