Java讀取指定目錄下的所有文件(子目錄里的文件也可遞歸得到)


 1 import java.io.File;
 2 
 3 public class ReadFile {
 4 
 5     public static void main(String[] args) {
 6 
 7         //     path是指定目錄的絕對路徑
 8         String path = "/Users/tonychan/Workspaces/MyEclipse 2017 CI/Zhangjiajie/WebRoot/pics";
 9         getFile(path);    
10 
11     }
12 
13     // 給定目錄的絕對路徑,獲取該目錄下的所有文件(子目錄的文件也可遞歸得到)
14     public static void getFile(String path) {
15         // File對象 可以是文件或者目錄
16         File file = new File(path);
17         File[] array = file.listFiles();
18 
19         for (int i = 0; i < array.length; i++) {
20             if (array[i].isFile()) {
21                 // only take file name
22                 System.out.println("^^^^^" + array[i].getName());
23                 // take file path and name
24                 System.out.println("#####" + array[i]);
25                 // take file path and name
26                 System.out.println("*****" + array[i].getPath());
27             } else if (array[i].isDirectory()) {
28                  getFile(array[i].getPath());
29             }
30         }
31     }
32 
33 }

 1. Mac下的路徑里的空格,在Java中不用轉義

String path = "/Users/tonychan/Workspaces/MyEclipse 2017 CI/Zhangjiajie/WebRoot/pics";

 2. File對象 可以是文件或者目錄

 3. File對象 涉及到的三個方法:

 

 

 

 
       


免責聲明!

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



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