Java實(shí)現(xiàn)復(fù)制文件夾及其子目錄

主要用遞歸的方法實(shí)現(xiàn)aa文件夾及其子目錄復(fù)制到bb文件夾。

代碼如下:

public class FileCopy {

  public static void main(String[] args) {

    try {

      copyDir("D:\\aa", "D:\\bb");

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

  public static void copyDir(String sourcePath, String newPath) throws IOException {

    File file = new File(sourcePath);

    String[] filePath = file.list();

    if (!(new File(newPath)).exists()) {

      (new File(newPath)).mkdir();

    }

    for (int i = 0; i < filePath.length; i++) {

      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 = new File(newPath);

    FileInputStream in = new FileInputStream(oldFile);

    FileOutputStream out = new FileOutputStream(file);

    byte[] buffer=new byte[2097152];

    while((in.read(buffer)) != -1){

      out.write(buffer);

    }

    out.close();

    in.close();

  }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容