在 Java 中檢查檔案是否存在\n


java.io.File 類提供檔案的有用方法。此示例演示如何使用 File 類的 file.exists() 方法檢查檔案是否存在。

示例

import java.io.File;

public class Main {
   public static void main(String[] args) {
      File file = new File("C:/java.txt");
      System.out.println(file.exists());
   }
}

結果

如果檔案“java.txt”存在於“C”盤,則上述程式碼示例將產生以下結果。

true

示例

以下是在 Java 中檢查檔案是否存在或不存在的另一個簡單示例。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintpWriter;

import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class fileexist {
   public static void main(String[] args) throws IOException {
      File f = new File(System.getProperty("user.dir")+"/folder/file.txt");
      System.out.println(f.exists());

      if(!f.getParentFile().exists()) {
          f.getParentFile().mkdirs();
      }        

      if(!f.exists()) {
         try {
            f.createNewFile();
         } catch (Exception e) {
            e.printStackTrace();
         }        
      }

      try {
         File dir = new File(f.getParentFile(), f.getName());
         PrintpWriter pWriter = new PrintpWriter(dir);
         pWriter.print("writing anything...");
         pWriter.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      }    
   }
}

輸出

如果檔案“java.txt”存在於“C”盤,則上述程式碼示例將產生以下結果。

true

更新時間:2020 年 6 月 18 日

5K+ 瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始
廣告