如何使用Java程序列出目录中的隐藏文件?

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//";
      //Creating the File object
      File directory = new File(filePath);
      //List of all files and directories
      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