How to check if a directory exists in java
There are many ways to check for the directory’s existence in Java.
The use of File.isDirectory()
is to check if the file denoted by a specified path is a directory or not. it returns true if the directory exists; false otherwise.
1). Using File.isDirectory()
package com.javacodestuffs.file.io;
import java.io.File;
public class CheckDirJava
{
public static void main(String[] args) {
String directoryPath = "/jvm/orcle-java-8/bin/";
File file = new File(directoryPath);
if (file.isDirectory()) {
System.out.println("Directory exist");
} else {
System.out.println("Directory doesn't exist.");
}
}
}
2). Using NIO
From Java 7 onward, we can make use of java.nio.file.Files
which provides several static methods that operate on files, directories, or other types of files. To simply check for a directory’s existence, we can use the method of java.nio.file.Files
the class. The Files.isDirectory()
returns true when your path points to a directory.
package com.javacodestuffs.file.io;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.File;
public class CheckDirUsingNIO {
public static void main(String[] args) {
String directoryPath = "/jvm/orcle-java-8/bin/";
Path path = Paths.get(directoryPath);
boolean isDir = Files.isDirectory(path);
if (isDir) {
System.out.println("Directory exist");
} else {
System.out.println("Directory doesn't exist.");
}
}
}
In this article, we have seen How to check if a directory exists in java with example. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment