Check if a directory exists in Java

In this source code example, we show you how to check if a directory exists in Java.

Check if a directory exists in Java

package com.javaguides.javaio.utility;

import java.io.File;

/**
 * Commonly used file utility methods.
 * @author javaguides.net
 *
 */
public class FileUtils {

    /**
     * Check if a directory exists
     * 
     * @param dir
     *            the directory to check
     * @return {@code true} if the {@code dir} exists on the file system
     */
    public static boolean exists(String dir) {
        File f = new File(dir);
        if (f.exists()) {
            return true;
        }
        return false;
    }
}

Using java.nio.file.Files

To check if a file or directory exists, we can leverage the Files.exists(Path) method.
Path path = Paths.get("sample.txt");
assertFalse(Files.exists(path));

Comments