Java遍歷一個目錄下的所有檔案
Java工具中為我們提供了一個用於管理檔案系統的類,這個類就是File類,File類與其他流類不同的是,流類關心的是檔案的內容,而File類關心的是磁碟上檔案的儲存。
一,File類有多個構造器,常用的構造器有:
1,public File(String pathname){}
在pathname路徑下建立檔案物件
2,public File(String path,String name){}
在path引數指定的目錄中建立具有給定名字的File物件,如果path為null,構造器將使用當前目錄建立物件
3,public File(File dir, String name){}
File物件dir表示一個目錄,在dir引數指定的目錄中建立具有給定名字的File物件,如果dir為null,
構造器將使用當前目錄建立物件
二,獲得檔案的許可權屬性:
1,表明檔案是否可讀,可寫,可執行
boolean canRead()
boolean canWrite()
boolean canExecute()
2,設定檔案的可讀,可寫,可執行
boolean setReadable(bollean state,bollean ownerOnly)
boolean setWritable((bollean state,bollean ownerOnly
)boolean setExecutable((bollean state,bollean ownerOnly)
3,刪除檔案
boolean delete()
如果檔案被刪除則返回true,否則返回false
void deleteOnExit()
在虛擬機器關閉時將檔案刪除
4,判斷檔案是否存在
boolean exists()
5,獲得檔案路徑名
String getCanonicalPath()
返回包含這個檔案的規範路徑名的字串該方法會使用恰當的目錄分隔符,並可以獲得底層檔案系統所選擇的大小寫處理方式
String getName()
返回包含這個File物件的檔名的字串,但不包含路徑資訊
6,判斷File為檔案還是目錄
boolean isDirectory()
判斷是否為一個目錄
boolean isFile()
判斷是否為一個檔案
7,獲得File物件包含的檔名和目錄名
String[] list()
返回這個File物件包含的檔名和目錄名構成的字元創陣列
String[] list(FilenameFilter filter)
返回有這個File物件包含的滿足過濾器條件的檔名和目錄名構成的字串陣列
File還有許多方法屬性,跟多的可以檢視API文件
現在,使用File類來遍歷一個目錄下的所有檔案,我的程式過程為:
1,獲取pathName的File物件
2,判斷該檔案或目錄是否存在,不存在時在控制檯輸出提醒
3,判斷如果不是一個目錄,就判斷是不是一個檔案,時檔案則輸出檔案路徑
4,獲取此目錄下的所有檔名與目錄名的字串陣列
5,如果是一個目錄,搜尋深度currentDepth+1,輸出目錄名後,進行遞迴
6,如果是檔案,則直接輸出檔名
程式如下:
import java.io.File;
import java.io.IOException;
public class DirErgodic {
private static int depth=1;
public static void find(String pathName,int depth) throws IOException{
int filecount=0;
//獲取pathName的File物件
File dirFile = new File(pathName);
//判斷該檔案或目錄是否存在,不存在時在控制檯輸出提醒
if (!dirFile.exists()) {
System.out.println("do not exit");
return ;
}
//判斷如果不是一個目錄,就判斷是不是一個檔案,時檔案則輸出檔案路徑
if (!dirFile.isDirectory()) {
if (dirFile.isFile()) {
System.out.println(dirFile.getCanonicalFile());
}
return ;
}
for (int j = 0; j < depth; j++) {
System.out.print(" ");
}
System.out.print("|--");
System.out.println(dirFile.getName());
//獲取此目錄下的所有檔名與目錄名
String[] fileList = dirFile.list();
int currentDepth=depth+1;
for (int i = 0; i < fileList.length; i++) {
//遍歷檔案目錄
String string = fileList[i];
//File("documentName","fileName")是File的另一個構造器
File file = new File(dirFile.getPath(),string);
String name = file.getName();
//如果是一個目錄,搜尋深度depth++,輸出目錄名後,進行遞迴
if (file.isDirectory()) {
//遞迴
find(file.getCanonicalPath(),currentDepth);
}else{
//如果是檔案,則直接輸出檔名
for (int j = 0; j < currentDepth; j++) {
System.out.print(" ");
}
System.out.print("|--");
System.out.println(name);
}
}
}
public static void main(String[] args) throws IOException{
find("D:\\MongoDB", depth);
}
}
測試截圖: