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(); }