利用Java IO中的字节流与缓冲流及单个或批量读写字节进行组合测试文件复制的速度....速度差别太大了!!!

本文探讨了不同文件复制方法的效率,包括不使用缓冲的批量字节读写、单字节读取拷贝、带缓冲区的逐字节读写及批量字节读取加缓冲区的方式,并发现使用批量字节读取加缓冲区的方法最快。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相同条件: 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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值