在 Java 中判斷檔案或目錄是否存在
java.io.File.exists() 方法用於檢查檔案或目錄是否存在。如果由 抽象路徑名稱指定的檔案或目錄存在,則此方法返回 true,如果不存在,則返回 false。
一個演示此方法的程式如下 −
示例
import java.io.File;
public class Demo {
public static void main(String[] args) {
try {
File file = new File("c:/JavaProgram/demo1.txt");
file.createNewFile();
System.out.println(file.exists());
} catch(Exception e) {
e.printStackTrace();
}
}
}上述程式的輸出如下 −
輸出
true
現在讓我們瞭解一下上述程式。
java.io.File.exists() 方法用於檢查檔案或目錄是否存在,並列印該方法返回的布林值。一個演示此方法的程式碼片段如下 −
try {
File file = new File("c:/JavaProgram/demo1.txt");
file.createNewFile();
System.out.println(file.exists());
} catch(Exception e) {
e.printStackTrace();
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP