在Java程序中,如何搜索(列出)目录中的所有文件?
以下示例说明如何使用File
类的dir.list()
方法搜索并获取指定目录下的所有文件的列表。
package com.yiibai;
import java.io.File;
public class SearchingFiles {
public static void main(String[] argv) throws Exception {
File dir = new File("F:\\worksp\\javaexamples\\java_directories");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist or is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
执行上面示例代码,得到以下结果 -
.classpath
.project
bin
dir11
myfile.txt
src
示例-2
以下是Java中列出目录中的所有文件的另一个示例。
package com.yiibai;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SearchingFiles2 {
public static void main(String[] args) throws IOException {
System.out.println("Enter the path to folder to search for files=> ");
Scanner s1 = new Scanner(System.in);
String folderPath = s1.next();
File folder = new File(folderPath);
if (folder.isDirectory()) {
File[] listOfFiles = folder.listFiles();
if (listOfFiles.length < 1)
System.out.println("There is no File inside Folder");
else
System.out.println("List of Files & Folder");
for (File file : listOfFiles) {
if (!file.isDirectory())
System.out.println(file.getCanonicalPath().toString());
}
} else
System.out.println("There is no Folder @ given path :" + folderPath);
}
}
执行上面示例代码,得到以下结果 -
Enter the path to folder to search for files =>
c:\
List of Files & Folder
C:\.rnd
C:\AVScanner.ini
C:\bootmgr
C:\BOOTNXT
C:\BOOTSECT.BAK
C:\DriverName.cfg
C:\file-for-download.txt
C:\grldr
C:\grldr.bak
C:\HaxLogs.txt
C:\LibAntiPrtSc_ERROR.log
C:\LibAntiPrtSc_INFORMATION.log
C:\okldr
C:\okldr.mbr
C:\report.rpt
C:\SecurityScanner.dll
C:\setup.log
C:\setupinfidb.db
C:\swapfile.sys
C:\Uninstall