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 檢查目錄是否存在