[英]How to solve my try-catch exception handling?
我在这里遇到try-catch exception
问题。 实际上,它的作用是提示用户输入文本文件的名称,例如Robot.txt,但是如果说该文件不存在,则必须确保应用程序提示用户输入文件名。 希望你们能理解我仍然是新手,所以请随时就我的编码等提供建议或意见。
主要方法类别:
import java.io.*;
import java.util.Scanner;
import java.util.Vector;
class TestVector3 {
public static void main(String [] args)
{
System.out.println("Please enter the name of the text file to read: ");
Scanner userInput = new Scanner(System.in);
Vector <KillerRobot> robotDetails = new Vector <KillerRobot>();
KillerRobot robot;
Scanner fileInput = null;
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :"); //Reprompt user for name of the text file
fileInput = new Scanner(userInput.nextLine());
}
while(fileInput.hasNext())
{
robot = new KillerRobot();
String first = fileInput.next();
robot.setName(first);
String second = fileInput.next();
robot.setMainWeapon(second);
int third = fileInput.nextInt();
robot.setNumberOfKills(third);
robotDetails.add(robot);
}
for(KillerRobot i : robotDetails)
{
System.out.println(i);
}
fileInput.close();
}
}
KillerRobot类文件:
class KillerRobot {
private String name;
private String mainWeapon;
private int numberOfKills;
KillerRobot()
{
}
public String getName()
{
return name;
}
public String getMainWeapon()
{
return mainWeapon;
}
public int getNumberOfKills()
{
return numberOfKills;
}
public String toString()
{
return name + " used a " + mainWeapon + " to destroy " + numberOfKills + " enemies ";
}
public void setName(String a)
{
name = a;
}
public void setMainWeapon(String b)
{
mainWeapon = b;
}
public void setNumberOfKills(int c)
{
numberOfKills = c;
}
}
当您声明自己是一个初学者时,让我们首先看一下代码的相关部分,以确保我们谈论的是同一件事:
Scanner fileInput = null;
try {
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
您有一个输入,并且您想检查此输入的条件,并需要一个新的输入, 直到满足该条件。 可以使用如下循环来解决此问题:
Scanner fileInput = null;
do {
System.out.println("Enter file name :");
try {
fileInput = new Scanner(new File(userInput.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
}
} while(fileInput == null);
那么最后,为什么这样做呢? fileInput
变量设置为null
并且将保持为null
直到从标准输入成功读取给定文件为止,因为会引发异常,否则将导致无法设置fileInput
变量。 此过程可以无休止地重复。
附带说明,出于性能原因,实现基于异常的控制流通常不是一个好主意。 最好通过File::exists
检查条件是否File::exists
。 但是,如果您在检查文件是否存在后读取文件,则该文件可能在此期间已被删除,从而引入了竞争状况。
对您的评论的答案 :在Java(或几乎所有编程语言)中,您可以内联表达式。 这意味着,与其在两个不同的语句中调用两个方法,不如在
Foo foo = method1();
Bar bar = method2(foo);
你可以简单地打电话
Bar bar = method2(method1());
这样,您可以节省一些空间(如果代码变长,它将变得越来越重要),因为您不需要在代码的任何其他位置保存在foo
中的值。 同样,您可以内联 (即调用此模式)
File file = new File(userInput.nextLine())
fileInput = new Scanner(file);
成
fileInput = new Scanner(new File(userInput.nextLine()));
因为file
变量仅在创建Scanner
时读取。
尝试将try-catch放入如下所示的循环中:
Scanner fileInput = null;
while (fileInput==null)
{
try
{
System.out.println("Please enter the file name.");
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
}
}
接下来,您可以考虑将“文件创建”部分移动到单独的方法中,从而使代码更简洁。
请勿尝试捕获,而应将其添加为功能。 对于运行时错误处理而言,异常自然而无逻辑生成。
检查文件在给定位置是否存在。
File textFile = new File(userInput.nextLine());
// Check if file is present and is not a directory
if(!textFile.exists() || textFile.isDirectory()) {
System.out.println("Error - file not found!");
//Reprompt user for name of the text file
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
如果要连续提示用户直到输入正确的路径,可以使用while循环代替if循环。
您可以像下面这样回调main()
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
main(args); // recursively call main() method
}
现在,如果用户首先尝试输入错误,则您的代码将要求重新输入文件名。
如何检查isFile是否存在?
File file = new File(filePathString);
if(file.exists() && !file.isDirectory()){
System.out.println("file exist");
}
这确实是一个XY问题,因为您假设检查文件是否存在的唯一方法是捕获 FileNotFoundException
(因此询问try-catch异常处理),而其他方法也可以帮助您以优雅的方式避免try-catch习惯用法。
要检查文件是否存在于给定路径中,可以简单地使用File.exists方法。 另请参阅File.isFile方法和/或File.isDirectory方法,以验证目标File对象的性质。
编辑:如raphw所述,此解决方案最适合在简单情况下使用,因为在文件存在检查过程中并发文件删除的情况下,它可能导致竞争状态。 请参阅他的答案以处理更复杂的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.