What is FileUtils.isDirectory() in Java?
Overview
isDirectory() is a FileUtils class that is used to check whether the specified file is a directory.
How to import FileUtils
The definition of FileUtils can be found in the Apache Commons IO package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
For other versions of the
commons-iopackage, refer to the Maven Repository.
You can import the FileUtils class as follows:
import org.apache.commons.io.FileUtils;
Syntax
public static boolean isDirectory(final File file, final LinkOption... options)
Parameters
final File file: This is the file to check.final LinkOption... options: These options indicate how symbolic links are handled.
Return value
This method returns true if the file is a directory. Otherwise, it returns false.
Code
import org.apache.commons.io.FileUtils;import java.io.File;public class Main{public static void main(String[] args) {// Example 1String filePath = "/Users/educative/Downloads";File file = new File(filePath);System.out.printf("The output of FileUtils.isDirectory(%s) is - %s", filePath,FileUtils.isDirectory(file));System.out.println();// Example 2filePath = "2.txt";file = new File(filePath);System.out.printf("The output of FileUtils.isDirectory(%s) is - %s", filePath,FileUtils.isDirectory(file));System.out.println();// Example 3filePath = "/usr/local/bin/perror";file = new File(filePath);System.out.printf("The output of FileUtils.isDirectory(%s) is - %s", filePath,FileUtils.isDirectory(file));}}
Explanation
Example 1
file - "/Users/educative/Downloads"
The method returns true, as the file is available and is a directory.
Example 2
file - 2.txt
The method returns false, as the file is not available.
Example 3
file - "/usr/local/bin/perror"
The method returns false, as the file is a symbolic link.
Output
The output of the code will be as follows:
The output of FileUtils.isDirectory(/Users/educative/Downloads) is - true
The output of FileUtils.isDirectory(2.txt) is - false
The output of FileUtils.isDirectory(/usr/local/bin/perror) is - false