Comparative byte stream buffer and the byte stream file copy

BufferedInputStream&BufferedOutputStream

  • When these two classes IO bit streams provided with Buffer operations, typically open the file for write or read operation, the buffer will add this flow pattern to improve the performance of the IO.

Input from an application into the file corresponds to a tank of water was poured into the other cylinder:

  1. FileOutputStream-> write () method is equivalent to the water drop by drop "transfer" in the past
  2. DataOutputStream-> writeXxx () method will be convenient, equivalent poured poured water "transfer" in the past
  3. BufferedOutputStream-> write method is more convenient, is equivalent to a floating poured into the bucket, then pour into the tub from another cylinder, improved performance
Single-byte, without a buffer file copies
/**
	 * 单字节,不带缓冲进行文件拷贝
	 * 文件拷贝最慢
	 */
	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();
	}
Byte stream using a buffered copy file
/**
	 * 进行文件的拷贝,利用带缓冲的字节流
	 * 文件拷贝适中
	 */
	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();
	}
File copy, read byte batch
/**
	  *文件拷贝,字节批量读取
	 *文件拷贝最快 
	 */
	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();
	}
Published 13 original articles · won praise 11 · views 235

Guess you like

Origin blog.csdn.net/wangailin666/article/details/105033302