java 移动文件和流读取那个快_JavaIO流-比较使用缓冲流和字节流复制文件效率

import org.junit.Test;

import java.io.*;

/**

* 比较使用缓冲流和字节流复制文件效率

* 缓冲流明显速度会快

* @author orz

*/

public class copyByBufferOrIOStream {

public void copyFileWithInputOutputStream(String srcPath,String destPath)

{

FileInputStream fis=null;

FileOutputStream fos=null;

try {

File file1=new File(srcPath);

File file2=new File(destPath);

fis=new FileInputStream(file1);

fos=new FileOutputStream(file2);

byte [] buffer=new byte[1024];

int len;

while ((len=fis.read(buffer))!=-1)

{

fos.write(buffer,0,len);

}

} catch (IOException e) {

e.printStackTrace();

}

finally {

try {

if(fos!=null)

{

fos.close();

}

} catch (IOException e) {

e.printStackTrace();

}

try {

if(fis!=null)

{

fis.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

public void copyFileWithBuffered(String srcPath,String destPath)

{

FileInputStream fis=null;

FileOutputStream fos=null;

BufferedInputStream bis=null;

BufferedOutputStream bos=null;

try {

File file1=new File(srcPath);

File file2=new File(destPath);

fis = new FileInputStream(file1);

fos=new FileOutputStream(file2);

bis=new BufferedInputStream(fis);

bos=new BufferedOutputStream(fos);

byte [] buffer=new byte[1024];

int len;

while ((len=bis.read(buffer))!=-1)

{

bos.write(buffer,0,len);

}

} catch (IOException e) {

e.printStackTrace();

}

finally {

//资源关闭

//要求:先关外层,再关里层

//关闭外层流的同时内层流也会自动的进行关闭,关于内层流的关闭,我们可以不管

try {

if(bos!=null)

{

bos.close();

}

} catch (IOException e) {

e.printStackTrace();

}

try {

if(bis!=null)

{

bis.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

@Test

public void test()

{

String srcPath="E:\\1.mp4";

String destPath2="E:\\2.mp4";

String destPath3="E:\\3.mp4";

long start1=System.currentTimeMillis();

copyFileWithBuffered(srcPath,destPath2);

long end1=System.currentTimeMillis();

//438

System.out.println("使用缓冲流复制花费操作时间为"+(end1-start1));

long start2=System.currentTimeMillis();

copyFileWithInputOutputStream(srcPath,destPath3);

long end2=System.currentTimeMillis();

//1469

System.out.println("使用字节流复制花费操作时间为"+(end2-start2));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值