如何在 Java 中檢查檔案是否在系統中的任何位置存在?
您可以使用 File 類和 Files 類兩種方式來驗證系統中是否存在特定檔案。
使用 File 類
java.io 包中的名為 File 的類表示系統中的檔案或目錄(路徑名)。此類提供了各種方法來對檔案/目錄執行各種操作。
此類提供各種方法來操作檔案,其中的 exists() 方法驗證當前 File 物件所表示的檔案或目錄是否存在,如果存在,則返回 true,否則返回 false。
示例
以下 Java 程式驗證指定檔案是否在系統中存在。它使用 File 類的方法。
import java.io.File;
public class FileExists {
public static void main(String args[]) {
//Creating a File object
File file = new File("D:\source\sample.txt");
//Verifying if the file exits
boolean bool = file.exists();
if(bool) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
}
}輸出
File exists
Files 類
從 Java 7 開始引入了 Files 類,它包含(靜態)方法,這些方法用於操作檔案、目錄或其他型別的檔案。
該類提供了一個名為 exists() 的方法,如果當前物件(s)所表示的檔案存在於系統中,則返回 true,否則返回 false。
示例
以下 Java 程式驗證指定檔案是否在系統中存在。它使用 Files 類的方法。
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileExists {
public static void main(String args[]) {
//Creating a Path object
Path path = Paths.get("D:\sample.txt");
//Verifying if the file exits
boolean bool = Files.exists(path);
if(bool) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
}
}輸出
File does not exist
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP