How to check if Filepath is Normal File or Directory in JAVA ?

In our previous post, we seen how to identify if a file is present or Not using JAVA

If you want to check whether certain filepath is a normal file or is a directory present in your disk before proceeding further to do some operations in JAVA, the java.io.File class provides an API “isFile()” and “isDirectory()” using which we can detect if filepath is normal file or directory.

$ vim FileIsDirectoryOrNormalFile.java
import java.io.File;

public class FileIsDirectoryOrNormalFile {
        private static void checkIfFilepathIsDirectoryOrFile(String filePath) {
                File filePointer = new File(filePath);

                if (filePointer.exists() && filePointer.isFile()) {
                        System.out.println("Filepath: " + filePath + " is a file");
                } else if (filePointer.exists() && filePointer.isDirectory()) {
                        System.out.println("Filepath: " + filePath + " is a Directory");
                } else if (!filePointer.exists()){
                        System.out.println("Filepath: " + filePath + " not be present");
                }
        }

        public static void main(String[] args) throws Exception {
                checkIfFilepathIsDirectoryOrFile("/opt/");
                checkIfFilepathIsDirectoryOrFile("/bin/ls");
                checkIfFilepathIsDirectoryOrFile("/opt/xml"); //some random name for file, which may not be present
        }
}

As, we can see in above program, we passed three different argument to our written function checkIfFilepathIsDirectoryOrFile, the first one is “/opt” which is a directory in Linux filesystem to demonstrate that our code detects its presence and shows that it is a Directory and second is “/bin/ls” which is a normal file in Linux filesystem, which we use as command to see files in current directory and third is “/opt/xml” which is a non-existent directory.

$ javac FileIsDirectoryOrNormalFile.java 
$ java FileIsDirectoryOrNormalFile 
Filepath: /opt/ is a Directory
Filepath: /bin/ls is a file
Filepath: /opt/xml not be present

The API definition is as below,

public boolean isFile () – Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise

public boolean isDirectory () – Tests whether the file denoted by this abstract pathname is a directory. Returnstrue if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise

Leave a Comment