The ListFiles() method returns an array containing objects (abstract paths) for all files (and directories) in the path represented by the current (File) object.
File Filter interface is a filter for filtering path names that can be passed as parameters to the listFiles() method. This method filters filenames based on the passed filter.
To get the hidden directories in a folder, implement a FileFilter that only accepts hidden directories and pass it as a parameter to the listFiles() method.
import java.io.File; import java.io.FileFilter; import java.io.IOException; public class Test{ public static void main(String args[]) throws IOException { //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); //Creating filter for directories files FileFilter fileFilter = new FileFilter(){ public boolean accept(File dir) { if (dir.isDirectory()&& dir.isHidden()) { return true; } else { return false; } } }; File[] list = directoryPath.listFiles(fileFilter); System.out.println("List of the jpeg files in the specified directory:"); for(File fileName : list) { System.out.println(fileName.getName()); System.out.println(fileName); } } }
List of the jpeg files in the specified directory: hidden directory1 D:\ExampleDirectory\hidden directory1 hidden directory2 D:\ExampleDirectory\hidden directory2
We can also use the isHidden() method of the Files class to get the list of hidden files −
import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.stream.Stream; public class Demo { public static void main(String[] args) throws IOException { File dir = new File("D:\ExampleDirectory"); File[] files = dir.listFiles(File::isHidden); Stream <File> fileStream = Arrays.stream(files); fileStream.forEach(file -> System.out.println(file.getName())); } }
D:\ExampleDirectory\hidden directory1 D:\ExampleDirectory\hidden directory2
The above is the detailed content of How to list hidden files in a directory in Java?. For more information, please follow other related articles on the PHP Chinese website!