【问题标题】:How to check if a file exists and loop to ask for new filename again if it doesn't exist?如何检查文件是否存在并循环以再次询问新文件名,如果它不存在?
【发布时间】:2014-05-11 13:30:00
【问题描述】:
public static String getFilename(Scanner getFile) throws FileNotFoundException { 
    System.out.print("\nEnter file name: ");
    String filename = getFile.next();
    File f = new File(filename);
    if (f.exists()) {
        System.out.println(filename + " exists.");
    } else {
        System.out.println(filename + " does not exist.");
        getFilename(getFile);
    }
    return filename;
}

这是我当前的代码。它要求我输入一些文本,然后检查我输入的输入是否是一个文件。
如果文件存在,我希望它返回存储文件名的字符串,返回到我的 main 方法。
如果它不存在,我希望我的方法重新启动(?)。我如何循环它?我当前的方法只是重新调用整个方法,但如果我运行此代码,任何不作为文件存在的输入/文件名都会出现错误。

【问题讨论】:

  • 你在做的是递归。您可能想要使用 forwhile 循环。

标签: java file loops


【解决方案1】:
File f = new File([filename]);
while(!f.exists()) {
    f = new File([newFilename]);
}
// Do what you want to do with the file.

这也允许您直接返回文件而不是文件名,但您可以像这样返回文件名:

String s = [filename];
File f = new File(s);
while(!f.exists()) {
    s = [newFilename];
    f = new File(s);
}
return s;

请记住,如果您不提供真实文件,这将无限循环。

【讨论】:

    【解决方案2】:

    循环正是您所需要的。在你的方法里面:

    String fileName = "";
    File f = new File(fileName);
    while(!f.exists()) {
        System.out.println("Enter file name: ");
        fileName = getFile.next();
        f = new File(fileName);
    }
    return f;
    

    基本上,代码会提示您输入文件,直到您输入存在的文件名。

    【讨论】:

    • NullPointerException 在第 3 行抛出 ... 尝试 do { ... } while(!f.exists());循环。
    【解决方案3】:

    这应该可以解决问题

    String filename = null;
    do{
        System.out.print("Enter file name: ");
        filename = getFile.nextLine();
    } while (!new File(filename).exists());
    

    在此循环之后,您确定filename 指的是存在的文件。

    【讨论】:

    • 猜我不会在我的上点击“发布”
    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 2013-02-06
    • 1970-01-01
    • 2012-04-11
    • 2017-11-22
    相关资源
    最近更新 更多