天天看點

java将一個檔案夾下的内容複制到另一個檔案夾下

package com.huangxt.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

/**
 * @Title: CopyDir
 * @Description:複制一個檔案夾的内容到另一個檔案夾
 * @Auther: huangxt
 * @Version: 1.0
 * @create 2019/6/18 15:24
 */
public class CopyDir {
    public static void copyDir(String sourcePath, String newPath) throws IOException {
        File file = new File(sourcePath);   //擷取檔案夾File對象
        String[] filePath = file.list();    //擷取檔案夾下所有内容的名稱

        if (!(new File(newPath)).exists()) {  //判斷要目标檔案夾是否存在不存在則建立
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {  //循環周遊
            //判斷是不是檔案夾,是的話執行遞歸。file.separator 分隔符,如“/”
            if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) {
                copyDir(sourcePath  + file.separator  + filePath[i], newPath  + file.separator + filePath[i]);
            }
            //判斷是不是檔案,是的話舊的檔案拷至新的檔案夾下
            if (new File(sourcePath  + file.separator + filePath[i]).isFile()) {
                copyFile(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }

        }
    }

    public static void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);//擷取舊的檔案File對象
        File file = new File(newPath);  //擷取新的檔案File對象并生成檔案
        FileInputStream in = new FileInputStream(oldFile);  //
        FileOutputStream out = new FileOutputStream(file);

        byte[] buffer=new byte[2097152];
        int readByte = 0;
        //讀取舊檔案的流寫入新檔案裡
        while((readByte = in.read(buffer)) != -1){
            out.write(buffer, 0, readByte);
        }

        in.close();
        out.close();
    }

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in); //啟用輸入
        System.out.println("請輸入源目錄:");
        String sourcePath = sc.nextLine();  //
        System.out.println("請輸入新目錄:");
        String path = sc.nextLine();

        //String sourcePath = "D://aa";
        //String path = "D://bb";

        copyDir(sourcePath, path);
    }
}

           

繼續閱讀