java實現文件夾(包括其中的子文件夾、子文件)的復制——遞歸


這是學校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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM