溫馨提示×

java file.exists異常處理

小樊
123
2024-08-18 17:48:36
欄目: 編程語言

在Java中,可以使用try-catch語句來捕獲文件不存在異常。當調用File.exists()方法時,如果文件不存在,會拋出一個FileNotFoundException異常。下面是一個簡單的示例代碼:

import java.io.File;

public class FileExistsExample {
    public static void main(String[] args) {
        File file = new File("test.txt");

        try {
            if (file.exists()) {
                System.out.println("File exists!");
            } else {
                System.out.println("File does not exist.");
            }
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
            // 可以在此處處理異常,比如創建文件,或者輸出日志
        }
    }
}

在上面的示例中,我們使用try-catch語句捕獲了文件不存在異常,并在catch語句塊中輸出了異常信息。您可以在catch語句塊中添加適當的處理邏輯,比如創建文件,或者輸出日志信息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女