java實現檔案夾(包括其中的子檔案夾、子檔案)的複製——遞迴

來源:互聯網
上載者:User

標籤:

這是學校java課的一道實驗題,題目如下:編程,根據指定的源和目標位置,完成指定檔案或檔案夾(包括其中的子檔案夾、子檔案)的複製。

以下是我的實現,使用了遞迴:

 1 package com.simon.myfinal; 2  3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.InputStream; 7  8 /** 9  * Created by Rainmer on 2015/6/28.10  */11 public class FileCopy {12     public static void main(String[] args) {13         String oldPath = "D:/bower";14         String newPath = "D:/bowerCopy";15         File dirNew = new File(newPath);16         dirNew.mkdirs();//可以在不存在的目錄中建立檔案夾17         directory(oldPath, newPath);18         System.out.println("複製檔案夾成功");19     }20 21     /**22      * 複製單個檔案23      * @param oldPath 要複製的檔案名稱24      * @param newPath 目標檔案名25      */26     public static void copyfile(String oldPath, String newPath) {27         int hasRead = 0;28         File oldFile = new File(oldPath);29         if (oldFile.exists()) {30             try {31                 FileInputStream fis = new FileInputStream(oldFile);//讀入原檔案32                 FileOutputStream fos = new FileOutputStream(newPath);33                 byte[] buffer = new byte[1024];34                 while ((hasRead = fis.read(buffer)) != -1) {//當檔案沒有讀到結尾35                     fos.write(buffer, 0, hasRead);//寫檔案36                 }37                 fis.close();38             } catch (Exception e) {39                 System.out.println("複製單個檔案操作出錯!");40                 e.printStackTrace();41             }42         }43     }44 45     /**46      *47      * @param oldPath 要複製的檔案夾路徑48      * @param newPath 目標檔案夾路徑49      */50     public static void directory(String oldPath, String newPath) {51         File f1 = new File(oldPath);52         File[] files = f1.listFiles();//listFiles能夠擷取當前檔案夾下的所有檔案和檔案夾53         for (int i = 0; i < files.length; i++) {54             if (files[i].isDirectory()) {55                 File dirNew = new File(newPath + File.separator + files[i].getName());56                 dirNew.mkdir();//在目標檔案夾中建立檔案夾57                 //遞迴58                 directory(oldPath + File.separator + files[i].getName(), newPath + File.separator + files[i].getName());59             } else {60                 String filePath = newPath + File.separator + files[i].getName();61                 copyfile(files[i].getAbsolutePath(), filePath);62             }63 64         }65     }66 }

 

java實現檔案夾(包括其中的子檔案夾、子檔案)的複製——遞迴

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.