字节缓冲流及字节流文件拷贝的比较

BufferedInputStream&BufferedOutputStream
  • 这两个流类位IO提供了带缓冲区的操作,一般打开文件进行写入 或读取操作时,都会加上缓冲,这种流模式提高了IO的性能。

从应用程序中把输入放入文件,相当于将一缸水倒入到另一个缸中:

  1. FileOutputStream—>write()方法相当于一滴一滴地把水“转移”过去
  2. DataOutputStream–>writeXxx()方法会方便一些,相当于一瓢一瓢把水“转移”过去
  3. BufferedOutputStream—>write方法更方便,相当于一飘一瓢先放入桶中,再从桶中倒入到另一个缸中,性能提高了
单字节,不带缓冲进行文件拷贝
/**
	 * 单字节,不带缓冲进行文件拷贝
	 * 文件拷贝最慢
	 */
	public static void copyFileByByte(File srcFile,File destFile)throws IOException{
		if(!srcFile.exists()){
			throw new IllegalArgumentException("文件:"+srcFile+"不存在");
		}
		if(!srcFile.isFile()){
			throw new IllegalArgumentException(srcFile+"不是文件");
		}
		FileInputStream in = new FileInputStream(srcFile);
		FileOutputStream out = new FileOutputStream(destFile);
		int c ;
		while((c = in.read())!=-1){
			out.write(c);
			out.flush();
		}
		in.close();
		out.close();
	}
利用带缓冲的字节流进行文件的拷贝
/**
	 * 进行文件的拷贝,利用带缓冲的字节流
	 * 文件拷贝适中
	 */
	public static void copyFileByBuffer(File srcFile,File destFile)throws IOException{
		if(!srcFile.exists()) {
			throw new IllegalArgumentException("文件:"+srcFile+"不存在");
		}
		
		if(!srcFile.isFile()) {
			throw new IllegalArgumentException(srcFile+"不是文件");
		}
		
		BufferedInputStream bis=new BufferedInputStream(
									new FileInputStream(srcFile));
		BufferedOutputStream bos=new BufferedOutputStream(
									new FileOutputStream(destFile));		
		int c;
		while((c=bis.read()) != -1) {
			bos.write(c);
			bos.flush();//刷新缓冲区
		}
		
		bis.close();
		bos.close();
	}
文件拷贝,字节批量读取
/**
	  *文件拷贝,字节批量读取
	 *文件拷贝最快 
	 */
	public static void copyFile(File srcFile,File destFile) throws IOException{
		if(!srcFile.exists()) {
			throw new IllegalArgumentException("文件:"+srcFile+"不存在");
		}
		
		if(!srcFile.isFile()) {
			throw new IllegalArgumentException(srcFile+"不是文件");
		}
		
		FileInputStream fis= new FileInputStream(srcFile);
		FileOutputStream fos=new FileOutputStream(destFile);
		byte[] b = new byte[8*1024];
		int bytes=0;
		while((bytes=fis.read(b,0,b.length)) !=-1) {
			fos.write(b,0,bytes);
			fos.flush();//最好加上
		}
		fis.close();
		fos.close();
	}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值