Java - File exists() 方法



描述

Java File exists() 方法測試由該抽象路徑名定義的檔案或目錄是否存在。

宣告

以下是 java.io.File.exists() 方法的宣告:

public boolean exists()

引數

返回值

當且僅當由抽象路徑名定義的檔案存在時,該方法返回布林值 true;否則返回 false。

異常

示例 1

以下示例演示了 Java File exists() 方法的用法。我們建立了一個 File 引用。然後,我們使用當前目錄中不存在的 test.txt 建立一個 File 物件。然後,我們使用 createNewFile() 方法建立檔案。現在,使用 exists() 方法,我們檢查檔案是否已建立。然後,如果檔案存在,我們將刪除該檔案,並在再次使用 exists() 方法檢查後列印狀態。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      boolean bool = false;      
      try {
         // create new files
         f = new File("test.txt");
         
         // create new file in the system
         f.createNewFile();
         
         // tests if file exists
         bool = f.exists();
         
         // prints
         System.out.println("File exists: "+bool);
         
         if(bool == true) {
            // delete() invoked
            f.delete();
            System.out.println("delete() invoked");
         }
         
         // tests if file exists
         bool = f.exists();
         
         // prints
         System.out.print("File exists: "+bool);
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

File exists: true
delete() invoked
File exists: false

示例 2

以下示例演示了 Java File exists() 方法的用法。我們建立了一個 File 引用。然後,我們使用提供的目錄中存在的 F:/test.txt 建立一個 File 物件。現在,使用 exists() 方法,我們檢查檔案是否存在。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      boolean bool = false;      
      try {
         // create new files
         f = new File("F:/test.txt");         
    
         // tests if file exists
         bool = f.exists();
         
         // prints
         System.out.println("File exists: "+bool);
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

File exists: true

示例 3

以下示例演示了 Java File exists() 方法的用法。我們建立了一個 File 引用。然後,我們使用提供的目錄中存在的 F:/test 目錄建立一個 File 物件。現在,使用 exists() 方法,我們檢查目錄是否存在。

package com.tutorialspoint;
import java.io.File;
public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      boolean bool = false;      
      try {
         
         // create new files
         f = new File("F:/test");         
    
         // tests if file exists
         bool = f.exists();
         
         // prints
         System.out.println("Directory exists: "+bool);
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Directory exists: true
java_file_class.htm
廣告
© . All rights reserved.