大写转换

时间:2018-11-28 05:22:41

标签: java try-catch

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.");
    }

}

运行代码时,检查输入的文件是否存在的验证不会运行,而是终止程序。我可以使用try / catch吗?

1 个答案:

答案 0 :(得分:0)

您可以做三件事

1。删除System.exit()

2。添加空值,然后再使用文件对象

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

3。添加try catch块以处理您的情况FileNotFoundException中可能出现的异常。