java 检查目录是否存在
We are using the File class that is an abstract representation of file and directory path. To check if a directory exists we have to follow a few steps:
我们正在使用File类 ,它是文件和目录路径的抽象表示。 要检查目录是否存在,我们必须执行以下步骤:
Create a File object and at the time of instantiation, we have to give abstract path there for which we will be in searching.
创建一个File对象 ,在实例化时,我们必须在其中提供抽象路径,以便进行搜索。
By using exists() method of File. This method tests whether the directory exists. The return type of this method is boolean so it returns true if and only if the directory exists and otherwise it will return false.
通过使用File的exist()方法。 此方法测试目录是否存在。 此方法的返回类型为boolean,因此仅当目录存在时,它才返回true,否则它将返回false。
We will understand clearly with the help of an example.
我们将通过一个示例清楚地了解。
Example:
例:
import java.io.File;
public class ToCheckDirectoryExists {
public static void main(String[] args) {
File dir_path1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles");
File dir_path2 = new File("C:\\Users\\computer clinic\\Articles");
// By using exists() method of File will check whether the
// specified directory exists or not and exist() method works
// with File class object because of its File method and
// it return Boolean return true if directory exists false otherwise.
boolean dir_exists1 = dir_path1.exists();
boolean dir_exists2 = dir_path2.exists();
// By using getPath()method to retrieve the given path of the
// directory and dir_exists1 and dir_exists1 returns true
// when directory exists else false.
System.out.println("Given Directory1 " + dir_path1.getPath() + " exists: " + dir_exists1);
System.out.println("Given Directory2 " + dir_path2.getPath() + " is not exists: " + dir_exists2);
}
}
Output
输出量
D:\Programs>javac ToCheckDirectoryExists.java
D:\Programs>java ToCheckDirectoryExists
Given Directory1 C:\Users\computer clinic\OneDrive\Articles exists: true
Given Directory2 C:\Users\computer clinic\Articles is not exists: false
翻译自: https://www.includehelp.com/java/how-to-check-if-directory-exists-in-java.aspx
java 检查目录是否存在