Как отобразить мое собственное сообщение FileNotFoundException - PullRequest
0 голосов
/ 20 февраля 2019

У меня проблема с созданием пользовательских исключений в Java.В частности, я хотел бы преднамеренно выдать исключение FileNotFoundException, чтобы протестировать метод с именем fileExists ().Метод проверяет, не существует ли файл (A), (b) не является обычным файлом или (c) недоступен для чтения.Он печатает разные сообщения для каждой ситуации.Однако при выполнении следующего кода основной метод отображает сообщение об исключении 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;

}

Ответы [ 2 ]

0 голосов
/ 20 февраля 2019

В качестве альтернативы вы также можете создать класс, в котором расширение FileNotFoundException присваивает ему File в качестве параметра, а затем выбрасывает его в свой улов вместо этого и переопределяет ваши распечатки в указанном классе.

0 голосов
/ 20 февраля 2019

Прежде всего вы можете захотеть избегать использования тех же имен классов, что и существующие классы 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());
    }
}
...