copyFileByBytes:47ms
copyFileByDataOutputStream:31ms
copyFileByBufferedOutputStream:49ms
//排除時(shí)間誤差,三種方法基本一樣.
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(); }
2014-11-03
把flush拿到循環(huán)外面,不影響文件完整性.經(jīng)MD5校驗(yàn),三種方法考貝的文件和原始文件一致.不知道是不是像前面同學(xué)說(shuō)的,后臺(tái)緩沖區(qū)滿了會(huì)自動(dòng)flush.