Java程式檢查檔案是否存在


在本文中,我們將學習如何使用Java檢查檔案是否存在。程式演示瞭如何使用java.io.File類的exists()方法來執行此檢查。

Java.io.File.exists()方法

java.io.File.exists()方法如果檔案路徑存在,則返回true,否則返回false。引數:此方法不接受任何引數。返回值:它返回一個布林值,指示由抽象路徑指定的檔案是否存在。

在Java中檢查檔案是否存在

以下是檢查檔案是否存在的方法:−

  • 步驟1. 使用Try-Catch塊:在檔案建立或檢查期間可能發生的任何異常,都使用try-catch塊來處理。
  • 步驟2. 建立檔案物件:使用檔名“demo1.txt”建立一個File物件。
File file = new File("demo1.txt");
  • 步驟3. 建立新檔案:呼叫createNewFile()方法,如果檔案不存在則建立它。
file.createNewFile();
  • 步驟4. 檢查檔案是否存在:使用exists()方法檢查檔案是否存在。

Java程式檢查檔案是否存在

演示此功能的程式如下:−

import java.io.File;
public class Demo {
	public static void main(String[] args) {
		try {
			File file = new File("demo1.txt");
			file.createNewFile();
			System.out.println("File exists? " + file.exists());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

輸出

File exists? true

更新於: 2024年11月23日

189次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.