在 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();
}

更新時間:2019 年 7 月 30 日

6 千次檢視

啟動你的職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.