亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

copyFileByBytes:47ms

copyFileByDataOutputStream:31ms

copyFileByBufferedOutputStream:49ms

//排除時間誤差,三種方法基本一樣.

	public?static?void?copyFileByBytes(File?from,?File?to)?throws?IOException?{
		if?(!from.exists())?{
			System.out.println("文件不存在");
		}
		if?(!from.exists())?{
			System.out.println(from?+?"不是文件");
			//?throw?InterceptorOperations
			//?throw?IORInterceptor;
		}
		FileOutputStream?fos?=?new?FileOutputStream(to);
		FileInputStream?fis?=?new?FileInputStream(from);
		byte[]?buf?=?new?byte[1024?*?1024];
		int?b;
		while?((b=fis.read(buf))?!=?-1)?{
			fos.write(buf,?0,?b);
//			fos.flush();
		}
		fos.flush();
		fos.close();
		fis.close();
	}

	public?static?void?copyFileByDataOutputStream(File?from,?File?to)
			throws?IOException?{
		if?(!from.exists())?{
			throw?new?IllegalArgumentException("文件:"?+?from.getAbsolutePath()
					+?"不存在");
		}
		if?(!from.exists())?{
			throw?new?IllegalArgumentException(from?+?"不是文件,可能是文件夾");
			//?throw?InterceptorOperations
			//?throw?IORInterceptor;
		}
		DataOutputStream?dos?=?new?DataOutputStream(new?FileOutputStream(to));
		DataInputStream?dis?=?new?DataInputStream(new?FileInputStream(from));

		int?i;
		byte[]?buf?=?new?byte[1024?*?1024];
		while?((i?=?dis.read(buf,?0,?buf.length))?!=?-1)?{
			dos.write(buf,?0,?i);
			
		}
		dos.flush();
		dos.close();
		dis.close();
	}

	public?static?void?copyFileByBufferedOutputStream(File?from,?File?to)
			throws?IOException?{
		if?(!from.exists())?{
			throw?new?IllegalArgumentException("文件:"?+?from.getAbsolutePath()
					+?"不存在");
		}
		if?(!from.exists())?{
			throw?new?IllegalArgumentException(from?+?"不是文件,可能是文件夾");
			//?throw?InterceptorOperations
			//?throw?IORInterceptor;
		}
		BufferedOutputStream?bos?=?new?BufferedOutputStream(new?FileOutputStream(to));
		BufferedInputStream?bis?=?new?BufferedInputStream(new?FileInputStream(from));

		int?i;
		byte[]?buf?=?new?byte[1024?*?1024];
		while?((i?=?bis.read(buf,?0,?buf.length))?!=?-1)?{
			bos.write(buf,?0,?i);
			
		}
		bos.flush();
		bos.close();
		bis.close();
	}
	


正在回答

1 回答

把flush拿到循環外面,不影響文件完整性.經MD5校驗,三種方法考貝的文件和原始文件一致.不知道是不是像前面同學說的,后臺緩沖區滿了會自動flush.

0 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
文件傳輸基礎——Java IO流
  • 參與學習       133821    人
  • 解答問題       1060    個

為您介紹IO流的使用,以及對象的序列化和反序列化的內容

進入課程
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號