java nio 复制文件

周末无聊。学习了一下nio,就拿他写了个读写文件的,和老的比了一下,速度真的快了很多,后来又用FastCopy 这个小工具比了一下,发现速度差不多,FastCopy 比直接右键复制 黏贴要快很多。下面是代码:

package com.lucene.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileCopy {
public static String src = "f:\\永远强大.rmvb";
public static String dist = "f:\\永远强大2.rmvb";

/**
* @param args
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();
copyOld();
long end = System.currentTimeMillis();
System.out.println("nio 用时: " + (end - start));

long start2 = System.currentTimeMillis();
copyOld();
end = System.currentTimeMillis();
System.out.println("io 用时: " + (end - start2));
}

public static void copyOld() {
File srcFile = new File(src);
File distFile = new File(dist);
if (distFile.exists()) {
distFile.delete();
}
try {
FileInputStream fin = new FileInputStream(srcFile);
BufferedInputStream buffIn = new BufferedInputStream(fin);

FileOutputStream fout = new FileOutputStream(distFile);
BufferedOutputStream buffout = new BufferedOutputStream(fout);
byte[] bytes = new byte[1024];
while (buffIn.read(bytes) > 0) {
buffout.write(bytes);
}
fin.close();
buffIn.close();
fout.close();
buffout.close();
} catch (Exception e) {
e.printStackTrace();
}

}

public static void copyNew() {
try {
File srcFile = new File(src);
File distFile = new File(dist);
if (distFile.exists()) {
distFile.delete();
}

FileInputStream fin = new FileInputStream(srcFile);
FileOutputStream fout = new FileOutputStream(distFile);
FileChannel inChannel = fin.getChannel();
FileChannel outChannel = fout.getChannel();
int ByteBufferSize = 1024 * 100;
ByteBuffer buff = ByteBuffer.allocate(ByteBufferSize);

while (inChannel.read(buff) > 0) {
buff.flip();
if (inChannel.position() == inChannel.size()) {// 判断是不是最后一段数据
int lastRead = (int) (inChannel.size() % ByteBufferSize);
byte[] bytes = new byte[lastRead];
buff.get(bytes, 0, lastRead);
outChannel.write(ByteBuffer.wrap(bytes));
buff.clear();
} else {
outChannel.write(buff);
buff.clear();
}
}// 这个使用FileChannel 自带的复制
// outChannel.transferFrom(inChannel, 0, inChannel.size());
outChannel.close();
inChannel.close();
fin.close();
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值