CodeGym /Java Blog /Toto sisi /Java 判斷文件是否存在的方法
John Squirrels
等級 41
San Francisco

Java 判斷文件是否存在的方法

在 Toto sisi 群組發布

為什麼我們需要檢查文件是否“存在”?

在處理文件操作(讀/寫/創建/刪除/更新等)時,許多新手可能想知道為什麼我們甚至需要檢查文件是否存在?對此的適當回應是,為了避免NoSuchFileException,訪問文件始終是一種更安全的方式。因此,您需要在訪問文件之前檢查文件是否存在,以避免任何運行時異常。Java 中如何判斷一個文件是否存在 - 1

如何使用 file.exists() 方法進行檢查?

Java 提供了一個簡單的布爾方法file.exists(),它不需要任何參數來檢查給定路徑上的相關文件。檢查文件是否存在時,請考慮 3 種情況。
  • 文件已找到。
  • 找不到該文件。
  • 如果未授予權限(出於安全原因),文件狀態未知。
如果找到文件,File.exists()方法返回“ true ”。如果找不到或訪問失敗,則返回“ false ”。

例子

讓我們看一個簡單的代碼示例來了解實現。

package com.java.exists;
import java.io.File;

public class ExistsMethodInJava {

	public static void main(String[] args) {

		String filePath = "C:\\Users\\Lubaina\\Documents\\myNewTestFile.txt";
		File file = new File(filePath);

		// check if the file exists at the file path
		System.out.println("Does File exists at \"" + filePath + "\"?\t" + file.exists());
		
		filePath = "C:\\Users\\Lubaina\\Documents\\myOtherTestFile.txt";
		File nextFile = new File(filePath);
		
		// check if the file exists at the file path
		System.out.println("Does File exists at \"" + filePath + "\"?\t" + nextFile.exists());
	}
}
輸出
文件是否存在於“C:\Users\Lubaina\Documents\myNewTestFile.txt”?true 文件是否存在於“C:\Users\Lubaina\Documents\myOtherTestFile.txt”?錯誤的
請注意file.exists()方法也適用於“目錄”路徑。如果您使用此方法檢查有效的目錄路徑,它將返回 true 否則返回 false。為了更好地理解,您可以查看以下代碼塊。

package com.java.exists;
import java.io.File;

public class CheckFileExists {

	// check if the "file" resource exists and not "directory"
	public static boolean checkFileExists(File file) {
		return file.exists() && !file.isDirectory();
	}

	public static void main(String[] args) {

		String directoryPath = "C:\\Users\\Lubaina\\Documents\\javaContent";
		File direcotry = new File(directoryPath);

		// check if the directory exists at the dir path
		if (direcotry.exists()) {
			System.out.println("Direcotry at \"" + directoryPath + "\" exists.\n");
		} else {
			System.out.println("Direcotry at \"" + directoryPath + "\" does not exist.\n");
		}

		// check if the resource present at the path is a "file" not "directory"
		boolean check = checkFileExists(direcotry);
		System.out.println("Is the resource \"" + direcotry + "\" a File? " + check);

		String filePath = "C:\\Users\\Lubaina\\Documents\\myNewTestFile.txt";
		File file = new File(filePath);
		check = checkFileExists(file);
		System.out.println("Is the resource \"" + file + "\" a File? " + check);
	}
}
輸出
“C:\Users\Lubaina\Documents\javaContent”目錄存在。資源“C:\Users\Lubaina\Documents\javaContent”是一個文件嗎?false 資源“C:\Users\Lubaina\Documents\myNewTestFile.txt”是一個文件嗎?真的
從輸出中可以看出,名為“javaContent”的目錄已通過exists()方法驗證。所以如果你特別想檢查一個文件是不是目錄,可以使用Java中 File類提供的boolean方法isDirectory() 。

結論

到本文結束時,您必須熟悉如何在 Java 中檢查文件是否存在。您可以編寫自己的程序來測試和理解此功能。一旦您熟悉了它,您也可以探索檢查文件是否存在的其他方法(例如,使用符號鏈接或 nio 類)。祝你好運,編碼愉快!:)
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION