在Java编程中,复制文件的方法有很多,而且经常要用到。大伙一般都是用缓冲输入输出流来实现的(绝大多数人都是如此),实际上还存在另一种方法,用文件通道(FileChannel)来实现文件复制竟然比用老方法快了近三分之一。下面我就来介绍一下如何用文件通道来实现文件复制,以及在效率上的对比
1.用文件通道的方式来进行文件复制
/**
* fileChannel方式
*/
public static void fileChannelCopy(File s, File t) {
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
try {
fi = new FileInputStream(s);
fo = new FileOutputStream(t);
in = fi.getChannel();//得到对应的文件通道
out = fo.getChannel();//得到对应的文件通道
in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fi.close();
in.close();
fo.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.用缓冲文件流得方法
/**
* 文件流方式
* @throws IOException
*/
public static void copy(File s,File t) throws IOException{
InputStream in=null;
OutputStream out=null;
try{
in= new BufferedInputStream(new FileInputStream(s));
out=new BufferedOutputStream(new FileOutputStream(t));
byte[] b=new byte[1024];
int flag=0;
while((flag=in.read(b))!=-1){
out.write(b, 0, flag);
}
}catch(Exception e){
}finally{
in.close();
out.close();
}
}
3.测试代码
public static void main(String[] args) throws IOException {
File s=new File("d:/tool/adt-bundle-windows-x86-20131030.zip");
File t=new File("e:/t.zip");
long start,end;
start = System.currentTimeMillis();
fileChannelCopy(s,t);
end = System.currentTimeMillis();
System.out.println("channel..."+(end-start));
start =System.currentTimeMillis();
copy(s,t);
end =System.currentTimeMillis();
System.out.println("copy..."+ (end-start));
}
4.测试结果
channel...365
copy...909
5.结论
由此可见,FileChannel复制文件的速度比BufferedInputStream/BufferedOutputStream复制文件的速度快 了近三分之一。在复制大文件的时候更加体现出FileChannel的速度优势。而且FileChannel是多并发线程安全的。