如何显示目录中的所有文件?(How to display all the files in a directory?)
优质
小牛编辑
127浏览
2023-12-01
问题描述 (Problem Description)
如何显示目录中的所有文件?
解决方案 (Solution)
下面的示例演示如何使用File类的list方法显示目录中包含的所有文件。
import java.io.*;
public class Main {
public static void main(String[] args) {
File dir = new File("C:");
String[] children = dir.list();
if (children == null) {
System.out.println( "Either dir 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);
}
}
}
}
结果 (Result)
上面的代码示例将产生以下结果。
build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test
以下是显示目录中所有文件的另一个示例。
import java.io.File;
public class ReadFiles {
public static File folder = new File("C:\\Apache24\\htdocs");
static String temp = "";
public static void main(String[] args) {
System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
listFilesForFolder(folder);
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
if (fileEntry.isFile()) {
temp = fileEntry.getName();
if ((temp.substring(temp.lastIndexOf('.')
+ 1, temp.length()).toLowerCase()).equals("txt"))System.out.println(
"File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
}
}
}
}
}
上面的代码示例将产生以下结果。
Reading files under the folder C:\Apache24\htdocs
File= C:\Apache24\htdocs\android\bkp\end.txt
File= C:\Apache24\htdocs\android\end.txt
File= C:\Apache24\htdocs\cpp_standard_library\images\code.txt
File= C:\Apache24\htdocs\java\Java - Data Structures.txt
File= C:\Apache24\htdocs\java\Java - Inheritance.txt
File= C:\Apache24\htdocs\scripts\easyui\changelog.txt