java—如何在仍然包含filenotfoundexception消息的情况下循环请求文件名?

sigwle7e  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(248)

我正在处理一个java程序的一部分,该程序试图读取项目文件夹中的文件。如果用户输入了一个不存在的文件名,我还会抛出一条“filenotfound”消息。但是,我正在努力尝试创建一个循环,该循环将重复,直到用户输入一个有效的文件名。以下是我的工作内容:

public class MyUtils {
    public static void readFile(String read) {
        File f = new File(read);
        try {
            Scanner sc = new Scanner(f);
            while(sc.hasNextLine()) {
                String info = sc.nextLine();
                System.out.println(info);
            }
            sc.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found. Try again: ");
        }       
    }
}

编辑我忘了包括调用此方法的位置。我道歉!请看这里:

System.out.print("Input file name: ");
String filetxt = sc.nextLine();
filetxt = filetxt.toLowerCase();
MyUtils.readFile(filetxt);
rks48beu

rks48beu1#

我将转换 readFile()Boolean 并根据您的代码的false的成功率进行布尔变量赋值,然后返回布尔变量。

public static Boolean readFile(String read) {
    Boolean isSuccess = false;
    File f = new File(read);
    try {
      Scanner sc = new Scanner(f);
      while(sc.hasNextLine()) {
        String info = sc.nextLine();
        System.out.println(info);
      }
      sc.close();
      isSuccess = true;
    } catch (FileNotFoundException e) {
      System.out.println("File not found. Try again: ");
      isSuccess = false;
    }
    return isSuccess;
}

接下来,你只要检查一下 readFile() 为false并询问用户另一个文件。

while(!MyUtils.readFile(filename)){
    filename = askAnotherFile();
}
af7jpaap

af7jpaap2#

您应该捕获函数外部的异常,如下所示:

public class MyUtils {

    public static void readFile(String read) throws FileNotFoundException {
        File f = new File(read);
        Scanner sc = new Scanner(f);
        while (sc.hasNextLine()) {
            String info = sc.nextLine();
            System.out.println(info);
        }
        sc.close();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Input file name: ");
        while (sc.hasNextLine()) {
            String filetxt = sc.nextLine();
            try {
                readFile(filetxt.toLowerCase());
            } catch (FileNotFoundException e) {
                System.out.println("File not found. Try again: ");
            }
        }
    }
}

相关问题