簡體   English   中英

如何顯示我自己的FileNotFoundException消息

[英]How to display my own FileNotFoundException message

我在Java中使用自定義異常引發問題。 具體來說,我想故意拋出FileNotFoundException以便測試稱為fileExists()的方法。 該方法測試文件(A)不存在,(b)不是普通文件還是(c)不可讀。 對於每種情況,它將打印不同的消息。 但是,運行以下代碼時,main方法顯示默認的FileNotFoundException消息,而不是fileExists方法中的消息。 我很想聽聽有關原因的任何想法。 所有變量都已聲明,但是我沒有在此處包括所有聲明。

public static void main (String[] args) throws Exception {
    try {

        inputFile = new File(INPUT_FILE);  // this file does not exist
        input = new Scanner(inputFile);
        exists = fileExists(inputFile);
        System.out.println("The file " + INPUT_FILE 
                + " exists. Testing continues below.");

    } catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }

}

public static boolean fileExists(File file) throws FileNotFoundException {
    boolean exists = false;    // return value
    String fileName = file.getName();  // for displaying file name as a String

    if ( !(file.exists())) {
        exists = false;
        throw new FileNotFoundException("The file " + fileName + " does not exist.");
    }

    else if ( !(file.isFile())) {
        exists = false;
        throw new FileNotFoundException("The file " + fileName + " is not a normal file.");
    }

    else if ( !(file.canRead())) {
        exists = false;
        throw new FileNotFoundException("The file " + fileName + " is not readable.");
    }

    else {
        exists = true;
    }

        return exists;

}

首先,您可能要避免使用與現有Java類相同的類名,以免造成混淆。

在您的main方法中,您需要在使用創建Scanner對象之前檢查文件是否存在。

另外,不需要所有的exists = false ,因為代碼在此停止,因此您將引發異常。

可能的解決方案如下:

public static boolean fileExists(File file) throws FileNotFoundException {
    String fileName = file.getName();  // for displaying file name as a String

    if (!(file.exists())) {
        throw new FileNotFoundException("The file " + fileName + " does not exist.");
    }

    if (!(file.isFile())) {
        throw new FileNotFoundException("The file " + fileName + " is not a normal file.");
    }

    if (!(file.canRead())) {
        throw new FileNotFoundException("The file " + fileName + " is not readable.");
    }

    return true;
}

public static void main(String[] args) throws Exception {
    String INPUT_FILE = "file.txt";

    try {
        File inputFile = new File(INPUT_FILE);

        if (fileExists(inputFile)) {
            Scanner input = new Scanner(inputFile);

            System.out.println("The file " + INPUT_FILE + " exists. Testing continues below.");
        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex.getMessage());
    }
}

您也可以選擇創建一個類,在該類中擴展FileNotFoundException,並為其提供文件File作為參數,然后將其放入catch中,並繼續覆蓋該類中的打印輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM