溫馨提示×

java怎么判斷文件路徑是否存在

小億
199
2024-06-03 20:03:21
欄目: 編程語言

在Java中,可以使用File類的exists()方法來判斷文件路徑是否存在。File.exists()方法返回一個boolean值,如果文件路徑存在則返回true,否則返回false。以下是一個示例代碼:

import java.io.File;

public class CheckFilePath {
    public static void main(String[] args) {
        String filePath = "C:/Users/username/Desktop/example.txt";

        File file = new File(filePath);

        if(file.exists()) {
            System.out.println("文件路徑存在");
        } else {
            System.out.println("文件路徑不存在");
        }
    }
}

在上面的示例中,我們先創(chuàng)建了一個File對象,然后使用exists()方法判斷文件路徑是否存在,并輸出相應(yīng)的提示信息。

0