如何使用 Java 程序列出目录中的隐藏文件?
java 8object oriented programmingprogramming更新于 2025/9/20 6:04:17
java.io 包中的 File 类表示系统中的文件或目录(路径名)。此类提供了多种方法来对文件/目录执行各种操作。
File 类的 isHidden() 方法用于验证当前 File 对象所表示的文件/目录(抽象路径)是否隐藏。
File 类的 ListFiles() 方法返回一个数组,该数组包含当前 File 对象所表示路径中所有文件(和目录)的对象(抽象路径)。
因此,要列出目录中所有隐藏文件,请使用 ListFiles() 方法获取所有文件对象,然后使用 isHidden() 方法验证每个文件是否隐藏。
示例
以下 Java 程序打印指定目录中所有隐藏文件和目录的文件名和路径 −
import java.io.File;
public class ListingHiddenDirectories {
public static void main(String args[]) {
String filePath = "D://ExampleDirectory//";
//创建 File 对象
File directory = new File(filePath);
//所有文件和目录的列表
File filesList[] = directory.listFiles();
System.out.println("List of files and directories in the specified directory:");
for(File file : filesList) {
if(file.isHidden()) {
System.out.println("File name: "+file.getName());
System.out.println("File path: "+file.getAbsolutePath());
}
}
}
}
输出
List of files and directories in the specified directory: File name: hidden_directory1 File path: D:\ExampleDirectory\hidden_directory1 File name: hidden_directory2 File path: D:\ExampleDirectory\hidden_directory2 File name: SampleHiddenfile1.txt File path: D:\ExampleDirectory\SampleHiddenfile1.txt File name: SampleHiddenfile2.txt File path: D:\ExampleDirectory\SampleHiddenfile2.txt File name: SampleHiddenfile3.txt File path: D:\ExampleDirectory\SampleHiddenfile3.txt

