Прописное преобразование - PullRequest
0 голосов
/ 28 ноября 2018
import java.util.Scanner;
import java.io.*;

public class UppercaseFileConverter {

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

        Scanner input = new Scanner(System.in);

        System.out.println("Enter the name of the file to be read: Here is the file converted into Uppercase.");
        String fileName = input.nextLine();

        File file = new File(fileName);
        Scanner inputFile = new Scanner(file);

        //validates that the file exists
        if (!file.exists()) {
            System.out.println("The file " + fileName + " does not exist or could not be opened.");
            System.exit(0);
        }

        //if file exists then reads each line and prints the upper case
        else {
            while (inputFile.hasNext()) {

                String line = inputFile.nextLine();

                System.out.println(line.toUpperCase());
            }
        }

        inputFile.close();
        System.out.println("Files read, converted and then closed.");
    }

}

Когда я запускаю свой код, моя проверка, которая проверяет, существует ли введенный файл, не запускается, а вместо этого завершает программу.Могу ли я использовать попытку / поймать?

1 Ответ

0 голосов
/ 28 ноября 2018

Вы можете сделать три вещи

1.Удалить System.exit()

2.Add null Проверьте перед использованием файлового объекта

if (file!=null&&!file.exists()) {}

3.Add try catchблок для обработки возможного исключения в вашем случае FileNotFoundException.

...