java拷貝目錄工具類

實現目錄拷貝,包括普通文件或文件夾拷貝,文件夾的拷貝會遞歸拷貝文件夾裏面的所有子文件。需要兩個參數:源文件路徑,拷貝後的目標路徑。例如源文件路徑爲A目錄下的"testSrcDir"這個文件夾,想要拷貝到跟A目錄同級的B目錄下,則目標路徑參數爲"B/testSrcDir"。以下爲源碼:

public class PathCopyUtil {

    public static void main(String[] args) throws IOException {
        File srcPath = new File("src");
        File destPath = new File("src_backup");
        if (COPY_OK == copyDirOrFile(srcPath, destPath)) {
            System.out.println("copy ok");
        } else {
            System.out.println("copy fail");
        }
    }
    
    public static final int COPY_OK = 0;
    public static final int ERROR_PATH_PARAM_NULL = 1;
    public static final int ERROR_SRC_PATH_NOT_EXIST = 2;
    public static final int ERROR_DEST_PATH_EXIST = 3;
    public static final int ERROR_IO = 4;
    
    public static int copyDirOrFile(File srcPath, File destPath) {
        if (srcPath == null || destPath == null) {
            return ERROR_PATH_PARAM_NULL;
        }
        if (!srcPath.exists()) {
            return ERROR_SRC_PATH_NOT_EXIST;
        }
        if (destPath.exists()) {
            return ERROR_DEST_PATH_EXIST;
        }
        
        if (srcPath.isFile()) {
            return copyFile(srcPath, destPath);
        } else {
            return copyDir(srcPath, destPath);
        }
    }
    
    private static int copyFile(File srcFile, File destFile) {
        FileInputStream is = null;
        FileOutputStream os = null;
        try {
            is = new FileInputStream(srcFile);
            byte buf[] = new byte[8 * 1024];
            int count = 0;
            os = new FileOutputStream(destFile);
            while ((count = is.read(buf)) != -1) {
                os.write(buf, 0, count);
            }
            return COPY_OK;
        } catch (IOException e) {
            e.printStackTrace();
            return ERROR_IO;
        } finally {
            closeIO(is);
            closeIO(os);
        }
    }
    
    private static void closeIO(Closeable io) {
        if (io != null) {
            try {
                io.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private static int copyDir(File srcDir, File destDir) {
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        for (File sub : srcDir.listFiles()) {
            File dest = new File(destDir, sub.getName());
            if (sub.isFile()) {
                int res = copyFile(sub, dest);
                if (res != COPY_OK) {
                    return ERROR_IO;
                }
            } else {
                int res = copyDir(sub, dest);
                if (res != COPY_OK) {
                    return ERROR_IO;
                }
            }
        }
        return COPY_OK;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章