★相同条件: src:桌面上文件 j2se70.chm, 大小 41.1MB ;dest:分别在桌面上创建一个新文件.
★结论:用数组批量读取+BufferedInputStream/BufferedOutputStream是速度最快的(259ms).简单太快了!!! (^_^) 而且字节数组只是设置了[1024], 当设置成[20*1024]时,时间为85ms.当然所需的cpu,内存等资源也会相应增加.
★后面再用字符流+内存流 的方式测一下速度如何.相信会更快!!!( ^_^ )
//文件复制
/** 1.读写方式:不使用缓冲,批量字节读写.(696ms)
*/
public static void copyFile(File src,File dest) throws IOException{
if(!src.exists()){
throw new IllegalArgumentException("文件"+src.getName()+"不存在");
}
if(!src.isFile()){
throw new IllegalArgumentException(src.getName()+"不是一个文件");
}
FileInputStream in=new FileInputStream(src);
//如果文件存在,则会先删除,再创建;如果文件不存在,则会直接创建这个新文件.
FileOutputStream out=new FileOutputStream(dest);
byte[] b=new byte[1024];
int bytes=0;
while((bytes=in.read(b))!=-1){
out.write(b, 0, bytes);
out.flush();
}
in.close();
out.close();
}
/*
* 2.读写方式:不使用缓冲,单字节读取进行拷贝.(208310ms)
*/
public static void copyByByte(File src,File dest) throws IOException{
if(!src.exists()){
throw new IllegalArgumentException("文件"+src.getName()+"不存在!");
}
if(!src.isFile()){
throw new IllegalArgumentException("要复制的对象"+src.getName()+"不是文件!");
}
FileInputStream fis=new FileInputStream(src);
FileOutputStream fos=new FileOutputStream(dest);
int i=0;
while((i=fis.read())!=-1){
fos.write(i);
}
fos.close();
fis.close();
}
/*
* 3.读写方式:带缓冲区,逐字节读写.(132047ms)
*/
public static void copyByBuffer(File src,File dest) throws IOException{
if(!src.exists()){
//抛出异常后程序就停止执行了吗?
throw new IllegalArgumentException("文件"+src.getName()+"不存在!");
}
if(!src.isFile()){
throw new IllegalArgumentException("要复制的对象"+src.getName()+"不是文件");
}
BufferedInputStream bis=new BufferedInputStream(
new FileInputStream(src));
BufferedOutputStream bos=new BufferedOutputStream(
new FileOutputStream(dest));
int i=0;
while((i=bis.read())!=-1){
bos.write(i);
bos.flush();
}
bis.close();
bos.close();
}
/*
* 4.读写方式:批量字节读取+缓冲区(259ms).
*/
public static void copyByBufferAndMass(File src,File dest) throws IOException{
if(!src.exists()){
throw new IllegalArgumentException("文件"+src.getName()+"不存在!");
}
if(!src.isFile()){
throw new IllegalArgumentException("要复制的对象:"+src.getName()+"不是文件!");
}
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(dest));
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(src));
int b=0;
byte[] buf=new byte[1024];
while((b=bis.read(buf))!=-1){
bos.write(buf, 0, b);
bos.flush();
}
bos.close();
bis.close();
}