字节流四种方式复制文件,速度对比

实验最好用视频这个比较大的文件做对比,否则看不出效果
代码:

public class test {
	public static void main(String[] args) throws IOException {
		
		Method1("D:\\视频\\1.avi","C:\\Users\\29265\\Desktop\\1.avi");
		Method2("D:\\视频\\1.avi","C:\\Users\\29265\\Desktop\\2.avi");
		Method3("D:\\视频\\1.avi","C:\\Users\\29265\\Desktop\\3.avi");
		Method4("D:\\视频\\1.avi","C:\\Users\\29265\\Desktop\\4.avi");
		
	}

	private static void Method4(String string, String string2) throws IOException {
		// TODO Auto-generated method stub
		//获取开始时间
		long start=System.currentTimeMillis();
		
		//用BufferedInputStream一次读取一个字节数组
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream(string));
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(string2));
		
		byte[] bt=new byte[1024];
		int len;
		while((len=bis.read(bt))!=-1){
			bos.write(bt,0,len);
		}
		//释放资源
		bis.close();
		bos.close();
		//获取结束时间
		long end=System.currentTimeMillis();
		 System.out.println("耗费时间:"+(end-start)+"毫秒!");
	}

	private static void Method3(String string, String string2) throws IOException {
		// TODO Auto-generated method stub
		//获取开始时间
		long start=System.currentTimeMillis();
		//用BufferedInputStream来一次读取一个字节
		//封装
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream(string));
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(string2));
		
		
		while(bis.read()!=-1){
			bos.write(bis.read());
		}
		
		//释放资源
		bis.close();
		bos.close();
		//获取结束时间
		long end=System.currentTimeMillis();
		System.out.println("耗费时间:"+(end-start)+"毫秒!");
		
	}

	private static void Method2(String string, String string2) throws IOException {
		// TODO Auto-generated method stub
		//获取开始时间
		long start=System.currentTimeMillis();
		//一次读取一个字节数组
		//封装
		FileInputStream fis=new FileInputStream(string);
		FileOutputStream fos=new FileOutputStream(string2);
		
		
		byte[] bt=new byte[1024];
		int len;
		while((len=fis.read(bt))!=-1){
			fos.write(bt,0,len);
		}
		
		//释放资源
		fis.close();
		fos.close();
		//获取结束时间
		long end=System.currentTimeMillis();
		System.out.println("耗费时间:"+(end-start)+"毫秒!");

	}

	private static void Method1(String string, String string2) throws IOException {
		// TODO Auto-generated method stub
		//获取开始时间
		long start=System.currentTimeMillis();
		
		//一次读取一个字节
		//封装
		FileInputStream fis=new FileInputStream(string);
		FileOutputStream fos=new FileOutputStream(string2);
		while(fis.read()!=-1){
			fos.write(fis.read());
		}
		
		//释放资源
		fis.close();
		fos.close();
		//获取结束时间
		long end=System.currentTimeMillis();
		System.out.println("耗费时间:"+(end-start)+"毫秒!");
	}
}

结果:

耗费时间:144951毫秒!
耗费时间:302毫秒!
耗费时间:375毫秒!
耗费时间:70毫秒!

速度对比可知:

A:一次读取一个字节数组比一次读取一个快
B:缓冲流比文件流更快
发布了210 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Ting1king/article/details/105012257