In this article, I will show how to get hidden files list
of a given directory using JAVA 8.
Tools Used :
1) eclipse version Luna 4.4.1.
2) Maven 3.3.3
3) JDK 1.8
Simple steps to follow are :
1) Create a simple maven project.
2) Write a simple java program to get hidden file list of given directory.
3) Run the program.
Use Case:
Suppose you want to filter all the hidden files in a directory.
Before JAVA 8,
(a) we have to write simple method that given a File tell you whether it’s hidden or not.
public boolean accept(File file){ return file.isHidden(); }
(b) To use this function, we need to wrap it into a FileFilter object that
you then pass to the File.listFiles method.
// Given implementation is Before JAVA 8 final File[] hiddenFiles = new File(".").listFiles(new FileFilter(){ public boolean accept(File file){ return file.isHidden(); } });
We can re-write the above test case in single line using
method references of JAVA 8 feature.
final File[] hiddenFiles = new File(".").listFiles(File::isHidden);
Write a simple java program to get hidden file list of given directory :
What is JAVA 8 method references ?
Once of most useful JAVA 8 feature is method references.
In simple words, this is an Analogously to using an object reference
when you pass an object around.
Like object reference, in JAVA 8 we can pass method references to any method as parameter
(called as lambda expressions).
Complete source code is Here,
HiddenFileListExample.java
package com.devjavasource.java8; import java.io.File; import java.io.FileFilter; public class HiddenFileListExample { public static void main(String[] args) { // Given implementation is Before JAVA 8 final File[] hiddenFiles = new File(".").listFiles(new FileFilter() { public boolean accept(File file) { return file.isHidden(); } }); // Simplified Using JAVA 8 - method references final File[] hiddenFilesInJava8 = new File(".") .listFiles(File::isHidden); System.out.println("Before JAVA 8: Hidden File List Example"); System.out.println("================================="); System.out.println("Before JAVA 8 - Hidden File List is: " + hiddenFiles.length); System.out.println("JAVA 8 - Hidden File List is: " + hiddenFilesInJava8.length); } }
Run the program :
Select HiddenFileListExample, Run As -> Java Application.
Out Put :
Before JAVA 8: Hidden File List Example ================================= Before JAVA 8 - Hidden File List is: 0 JAVA 8 - Hidden File List is: 0
You can download complete Project, Here
*** Venkat – Happy leaning ****