天天看點

java實作檔案夾的拷貝(複制檔案夾)

複制檔案夾其實就是通過遞歸複制檔案的過程,具體實作如下:

/**
     * 複制檔案夾(使用緩沖位元組流)
     * @param sourcePath 源檔案夾路徑
     * @param targetPath 目标檔案夾路徑
     */
    public static void copyFolder(String sourcePath,String targetPath) throws Exception{
        //源檔案夾路徑
        File sourceFile = new File(sourcePath);
        //目标檔案夾路徑
        File targetFile = new File(targetPath);

        if(!sourceFile.exists()){
            throw new Exception("檔案夾不存在");
        }
        if(!sourceFile.isDirectory()){
            throw new Exception("源檔案夾不是目錄");
        }
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        if(!targetFile.isDirectory()){
            throw new Exception("目标檔案夾不是目錄");
        }

        File[] files = sourceFile.listFiles();
        if(files == null || files.length == 0){
            return;
        }

        for(File file : files){
            //檔案要移動的路徑
            String movePath = targetFile+File.separator+file.getName();
            if(file.isDirectory()){
                //如果是目錄則遞歸調用
                copyFolder(file.getAbsolutePath(),movePath);
            }else {
                //如果是檔案則複制檔案
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(movePath));

                byte[] b = new byte[1024];
                int temp = 0;
                while((temp = in.read(b)) != -1){
                    out.write(b,0,temp);
                }
                out.close();
                in.close();
            }
        }
    }
           

測試

public static void main(String[] args) throws Exception {
        copyFolder("e:\\demo","e:\\demo2");
    }