[英]How do I call method if exception thrown?
I have a method called readinFile and if the user enters a wrong file instead of exiting I wanted to call the method readinFile again inside the readinFile method I ask the user for new filename. 我有一个称为readinFile的方法,如果用户输入错误的文件而不是退出,我想在readinFile方法内再次调用方法readinFile,请用户提供新的文件名。 The problem I am running into is the first time it goes through it and gives the exception file not found than it goes through the catch().
我遇到的问题是它第一次通过它并给出未找到的异常文件,而是它通过catch()。 I want it to call the method and not run the last inputStream.
我希望它调用该方法而不运行最后一个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");
}
You should generally not use exceptions for branching. 通常,不应将异常用于分支。 Just check for the existance of the file using File.exists, like so:
只需使用File.exists检查文件是否存在,如下所示:
new File(fileName).exists()
You probably want to do something like this: 您可能想要执行以下操作:
String fileName;
do {
System.out.println("Please enter filename");
fileName = getFileNameFromInput();
File file = new File(fileName);
} while (!file.exists());
readFile(file);
EDIT: 编辑:
As Bruno Reis has pointed out, this will only check if the file exists when the user specified the file name. 正如Bruno Reis指出的那样,这只会在用户指定文件名时检查文件是否存在。 If the file was to be moved/deleted between specifying the file name and reading it then a FileNotFoundException would still be thrown.
如果要在指定文件名和读取文件之间移动/删除文件,则仍然会引发FileNotFoundException。 To reduce the risk of this you can lock the file as discussed in this question .
为了降低这种风险,您可以按照本问题中的讨论锁定文件。
bool invalidFilename = true;
string fileName;
while(invalidFilename)
{
readinfile(...);
invalidFilename = !new File(fileName).exists();
}
inputStream = new Scanner(new FileInputStream(fileName));
You can check if the filename the user input does exists or not, and don't need to catch the exception. 您可以检查用户输入的文件名是否存在,并且不需要捕获异常。 (which is not a good design code, decrease the readability of the code)....
(这不是一个好的设计代码,会降低代码的可读性)。
as inflagranti said, 如无名氏所说,
you can do this pseudocode 你可以做这个伪代码
if (!new File(filename).exists()){
//read your other file from user
readinfile(....)
}
To get what you are after, without the chance of the file being deleted after you check for it existing but before you open it do something like: 要获得所需的信息,请先检查文件是否存在但在打开文件之前,不要将其删除:
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.