How do I get the hidden or visible files in a directory using a filter?
Author: Deron Eriksson
Description: This Java tutorial describes how to display the hidden or visible files in a directory using a filter from Commons IO.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
The HiddenFileFilter.HIDDEN and HiddenFileFilter.VISIBLE singleton instances in the ApacheSW Commons IOS library are filters that can be used to filter hidden and visible files (and directories), respectively. The ListHiddenAndVisibleFilesTest demonstrates this. It gets a listing of all the hidden files and directories in my project's root directory via directory.listFiles((FileFilter) HiddenFileFilter.HIDDEN); It then gets a listing of all visible files and directories in the same directory via directory.listFiles((FileFilter) HiddenFileFilter.VISIBLE); ListHiddenAndVisibleFilesTest.javapackage test; import java.io.File; import java.io.FileFilter; import java.io.IOException; import org.apache.commons.io.filefilter.HiddenFileFilter; public class ListHiddenAndVisibleFilesTest { public static void main(String[] args) throws IOException { File directory = new File("."); System.out.println("Hidden Files:"); File[] hiddenFiles = directory.listFiles((FileFilter) HiddenFileFilter.HIDDEN); for (File hiddenFile : hiddenFiles) { System.out.println("hidden file: " + hiddenFile.getCanonicalPath()); } System.out.println("\nVisible Files:"); File[] visibleFiles = directory.listFiles((FileFilter) HiddenFileFilter.VISIBLE); for (File visibleFile : visibleFiles) { System.out.println("visible file: " + visibleFile.getCanonicalPath()); } } } My project's directory contents are shown below. All files and directories are visible except hidden1.txt and hiddent2.txt. The output from executing ListHiddenAndVisibleFilesTest is shown here. ResultsHidden Files: hidden file: C:\projects\workspace\testing\hidden1.txt hidden file: C:\projects\workspace\testing\hidden2.txt Visible Files: visible file: C:\projects\workspace\testing\.classpath visible file: C:\projects\workspace\testing\.project visible file: C:\projects\workspace\testing\bin visible file: C:\projects\workspace\testing\docs visible file: C:\projects\workspace\testing\lib visible file: C:\projects\workspace\testing\src visible file: C:\projects\workspace\testing\stuff visible file: C:\projects\workspace\testing\visible1.txt visible file: C:\projects\workspace\testing\visible2.txt Related Tutorials:
|