Java List Files: Get All Files in Directory
In Java, you can use the File class to get all the files in a specified directory. You can use the listFiles() method to get all the files and subdirectories in the specified directory, returning an array of files. Then, you can loop through this file array to get the path and other properties of each file.
Here is an example code demonstrating how to retrieve all files in a specified directory.
import java.io.File;
public class ListFilesExample {
public static void main(String[] args) {
String directoryPath = "指定目录的路径"; // 替换为你想要获取文件的目录路径
File directory = new File(directoryPath);
// 检查目录是否存在
if (!directory.exists()) {
System.out.println("指定目录不存在。");
return;
}
// 获取目录下的所有文件和子目录
File[] files = directory.listFiles();
// 遍历文件数组
for (File file : files) {
// 检查文件是否是普通文件
if (file.isFile()) {
System.out.println("文件:" + file.getAbsolutePath());
}
}
}
}
Please note that the listFiles() method returns an array of files that includes all files and subdirectories within the directory. If you only want to get the files within the directory and not the subdirectories, you can exclude the subdirectories by using the isFile() method while iterating through the file array.