繁体   English   中英

如果引发异常,如何调用方法?

[英]How do I call method if exception thrown?

我有一个称为readinFile的方法,如果用户输入错误的文件而不是退出,我想在readinFile方法内再次调用方法readinFile,请用户提供新的文件名。 我遇到的问题是它第一次通过它并给出未找到的异常文件,而是它通过catch()。 我希望它调用该方法而不运行最后一个inputStream。

try 
{
    inputStream = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException E)
{
    readinfile(table, numberOfColumns, header,
               original, sntypes,displaySize, 
               writeOut,inputStream,fileName );
    System.out.print("It got here after doing the method call");        
}

通常,不应将异常用于分支。 只需使用File.exists检查文件是否存在,如下所示:

new File(fileName).exists()

您可能想要执行以下操作:

String fileName;

do {
    System.out.println("Please enter filename");
    fileName = getFileNameFromInput();
    File file = new File(fileName);
} while (!file.exists());

readFile(file);

编辑:

正如Bruno Reis指出的那样,这只会在用户指定文件名时检查文件是否存在。 如果要在指定文件名和读取文件之间移动/删除文件,则仍然会引发FileNotFoundException。 为了降低这种风险,您可以按照本问题中的讨论锁定文件。

bool invalidFilename = true;
string fileName;

while(invalidFilename)
{
    readinfile(...);   
    invalidFilename = !new File(fileName).exists();
}

inputStream = new Scanner(new FileInputStream(fileName));

您可以检查用户输入的文件名是否存在,并且不需要捕获异常。 (这不是一个好的设计代码,会降低代码的可读性)。

如无名氏所说,

你可以做这个伪代码

if (!new File(filename).exists()){
    //read your other file from user
    readinfile(....)

}

要获得所需的信息,请先检查文件是否存在但在打开文件之前,不要将其删除:

boolean done = false;
String fileName = fileNameParameter;

while(!done)
{
    try 
    {
        inputStream = new Scanner(new FileInputStream(fileName));
        done = true;
    }
    catch(FileNotFoundException E)
    {
        fileName = /* ask the user for the file name */
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM