package io_test;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class IoTest {public static void main(String[] args) {File fileSrcFile1 = new File("e:\\建立檔案夾.rar");File fileDestFile1 = new File("e:\\demo\\建立檔案夾.rar");File fileSrcFileF1 = new File("e:\\複件 建立檔案夾.rar");File fileDestFileF1 = new File("e:\\demo\\複件 建立檔案夾.rar");try {long start1 = System.currentTimeMillis();copyFile1(fileSrcFile1, fileDestFile1);long end1 = System.currentTimeMillis();System.out.println("copyFile1耗時:" + (end1 - start1) / 1000.0);long start2 = System.currentTimeMillis();copyFile2(fileSrcFileF1, fileDestFileF1);long end2 = System.currentTimeMillis();System.out.println("copyFile2耗時:" + (end2 - start2) / 1000.0);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 把源檔案的內容複寫到目標檔案 * * @param src * 源檔案 * @param dest * 目標檔案 */public static void copyFile1(File src, File dest) throws IOException {BufferedInputStream bis = null;BufferedOutputStream bos = null;byte[] b = new byte[8192];try {bis = new BufferedInputStream(new FileInputStream(src));bos = new BufferedOutputStream(new FileOutputStream(dest));for (int count = -1; (count = bis.read(b)) != -1;) {bos.write(b, 0, count);}bos.flush();} catch (IOException e) {throw e;} finally {close(bis);close(bos);}}/** * 把源檔案的內容複寫到目標檔案 * * @param srcFile * 源檔案 * @param destFile * 目標檔案 */public static void copyFile2(File srcFile, File destFile)throws IOException {FileInputStream input = new FileInputStream(srcFile);try {FileOutputStream output = new FileOutputStream(destFile);try {byte[] buffer = new byte[4096];int n = 0;while (-1 != (n = input.read(buffer))) {output.write(buffer, 0, n);}} finally {try {if (output != null) {output.close();}} catch (IOException ioe) {// ignore}}} finally {try {if (input != null) {input.close();}} catch (IOException ioe) {// ignore}}}/** * 同時關閉輸入資料流和輸出資料流,並把可能拋出的異常轉換成RuntimeException * * @param is * @param os */public static void close(InputStream is, OutputStream os) {close(is);close(os);}/** * 關閉輸入資料流的工具方法,並把可能拋出的異常轉換成RuntimeException * * @param is */public static void close(InputStream is) {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}/** * 關閉輸出資料流的工具方法,並把可能拋出的異常轉換成RuntimeException * * @param os */public static void close(OutputStream os) {if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}}