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

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();
	}
发布了13 篇原创文章 · 获赞 11 · 访问量 235

猜你喜欢

转载自blog.csdn.net/wangailin666/article/details/105033302