Check Hidden Files in Java
Tags: Java File Java IO Java NIO
Introduction
In this post we are going to explore how to use Java IO and Java NIO core classes to check if a file is hidden or not.
For example we have a text file is a hidden file located at D:\Files\file.txt
Using Java NIO Files.isHidden() static method
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesIsHiddenExample {
public static void main(String... args) {
try {
String fileName = "D:\\Files\\file.txt";
Path filePath = Paths.get(fileName);
boolean isHidden = Files.isHidden(filePath);
System.out.println("File [" + fileName + "] is hidden or not: " + isHidden);
} catch (IOException e) {
e.printStackTrace();
}
}
}
File [D:\Files\file.txt] is hidden or not: true
Using Java IO file.isHidden() method
import java.io.File;
public class FileIsHiddenExample {
public static void main(String... args) {
String fileName = "D:\\Files\\file1.txt";
File file = new File(fileName);
boolean isHidden = file.isHidden();
System.out.println("File [" + fileName + "] is hidden or not: " + isHidden);
}
}
File [D:\Files\file1.txt] is hidden or not: false
Notes about the hidden definition
On both methods above, the exact definition of hidden is system-dependent.
- On UNIX systems, a file is considered to be hidden if its name begins with a period character ‘.’.
- On Microsoft Windows systems, a file is considered to be hidden if it has been marked as such in the filesystem.
Happy Coding 😊