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));

}
}

猜你喜欢

转载自www.cnblogs.com/orzjiangxiaoyu/p/13399828.html