这是调试程序目的是计算它们的速度;
package com.leejuen.copy;
import java.io.File;
public class test {
public static void main(String[] args)
{
File s = new File("D:\\struts2帮助文档.rar");
File t = new File("E:\\struts2帮助文档.rar");
long start,end;
start = System.currentTimeMillis();
FileChannelCopy.ChannelCopy(s, t);
end = System.currentTimeMillis();
System.out.println(end-start);
start = System.currentTimeMillis();
Copy.copyBuf(s, t);
end = System.currentTimeMillis();
System.out.println(end-start);
}
}
这是普通的buf复制过程,这里要提醒的是buf是阻塞的复制后一定要关不close或flush缓冲区。要不然会有少部分数据留在缓冲区里没有复制
package com.leejuen.copy;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;
public class Copy {
public static void copyBuf(File s,File t)
{
InputStream bis = null;
OutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(s));
bos = new BufferedOutputStream(new FileOutputStream(t));
byte[] b = new byte[1024];
int i = 0;
while(bis.read(b)!=-1)
{
bos.write(b);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally
{
try {
bos.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
这是用channel管道复制过程
package com.leejuen.copy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileChannelCopy {
public static void ChannelCopy(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 (Exception e) {
// TODO: handle exception
}
finally{
try {
fi.close();
in.close();
fo.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
实验过程中当文件大小在比较小的情况(这里笔者没有生成足够多的文件来测试。不过这个比较小应该是在50~100M大小以下)以下时buf存储明显占优势。之后当文件使用100M的数据时FileChannel明显占优势。之后FileChannel就一直优势。所以选择什么方式复制要看复制的文件大小。不能一定的说那种方法就是好