package cn.yhy.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * 創建一個單獨的類,實現以下方法: * 1.判斷源文件是否存在; * 2.判斷目標文件父路徑是否存在,不存在則創建; * 3.實現複製操作; * @author yuhy * */ class CopyUtil{ private CopyUtil() {} public static boolean fileExists(String path) { //判斷源文件是否存在 return new File(path).exists(); } public static void creatParentDirectory(String path) { //創建父路徑 File file = new File(path); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } } public static boolean copy(String srcPath,String desPath) { //進行拷貝處理 boolean flag = false; //拷貝操作標記 File inFile = new File(srcPath); //實例化源文件 File outFile = new File(desPath); //實例化目標文件 InputStream input = null; OutputStream output = null; try { //InputStream類是一個抽象類,對文件進行處理使用FileInputStream類完成; //OutputStream類是一個抽象類,對文件進行處理使用FileOutputStream類完成; input = new FileInputStream(inFile); //字節輸入流 output = new FileOutputStream(outFile); //字節輸出流 copyHandle(input,output); //實際拷貝處理 flag = true; } catch (IOException e) { flag = false; } finally { try { input.close(); output.close(); } catch (IOException e) {} } return flag; } private static void copyHandle(InputStream input,OutputStream output) throws IOException { // 實際拷貝處理過程 long start = System.currentTimeMillis(); //獲得系統當前時間 int temp = 0; byte data[] = new byte[1024]; //創建一個字節數組 while ((temp = input.read(data)) != -1) { //不是-1,表示還有內容 output.write(temp); } long end = System.currentTimeMillis(); System.out.println("【統計】拷貝共花費時間:" + (end - start) + "毫秒"); } } public class Copy{ public static void main(String args[]) throws IOException { if (args.length != 2) { //源文件路徑及目標文件路徑是2個對象 System.out.println("執行方式錯誤,請按照java Copy 源文件路徑 目標文件路徑 進行執行"); System.exit(1); //系統退出 } if (CopyUtil.fileExists(args[0])) { //如果源文件存在,則進行拷貝 CopyUtil.creatParentDirectory(args[1]); //創建目標文件路徑 System.out.println(CopyUtil.copy(args[0], args[1]) ? "文件拷貝完成!" : "文件拷貝出現錯誤!"); //三元表達式 } else { System.out.println("拷貝未能進行,源文件不存在!"); } } }