Java Read Files Directory Guide
In Java, the File class can be used to read files in a specified directory. Below is a simple example:
import java.io.File;
public class ReadFilesInDirectory {
public static void main(String[] args) {
// 指定目录路径
String directoryPath = "path/to/directory";
// 创建File对象
File directory = new File(directoryPath);
// 判断目录是否存在
if (directory.exists() && directory.isDirectory()) {
// 获取目录下的文件列表
File[] files = directory.listFiles();
// 遍历文件列表
for (File file : files) {
// 判断是否为文件
if (file.isFile()) {
System.out.println(file.getName()); // 输出文件名
}
}
} else {
System.out.println("目录不存在或不是一个目录");
}
}
}
In the above example, start by creating a File object using the specified directory path. Then, use the exists() and isDirectory() methods of the File object to check if the directory exists and is indeed a directory. If the directory exists and is a directory, use the listFiles() method to get the list of files in the directory. Finally, loop through the file list and output the name of each file.
Please make sure to replace the variable “directoryPath” in the example code with the path of the directory you want to read.