Check if file is hidden

This example will demonstrate how to test whether the file is a hidden file in java. File meta data is stored within the file system and directories. It tracks information about each of the file which is typically referred to as file attributes. File attributes include size of a file, is it a directory, a symbolic link, a regular file, determine if the file is hidden, retrieve the last modified time and find when a file was created. In the set up we will named a file that will be referenced in all snippets below.

Setup

private static final String SOURCE = "com/levelup/java/io/file-is-hidden.txt";

Path source;

@Before
public void setUp () throws IOException, URISyntaxException {

    source = Paths.get(this.getClass().getClassLoader().getResource(SOURCE).toURI());
}

Straight up Java

File.isHidden

Tests whether the file named by this abstract pathname is a hidden file. 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.

@Test
public void check_if_file_is_hidden_java () {

    File file = source.toFile();

    if (file.isHidden()) {
        logger.info("File is hidden");
    } else {
        logger.info("File not hidden");
    }
}

Java 7 File I/O

Tells whether or not a file is considered hidden using java 7 file NIO. Be aware that the definition of hidden is platform or provider dependent so be sure to check the java docs for more detail.

@Test
public void check_if_file_is_hidden_nio () throws IOException {

    boolean isHidden = Files.isHidden(source);

    assertFalse(isHidden);
}