Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何解决我的try-catch异常处理?_Java_Exception_Try Catch - Fatal编程技术网

Java 如何解决我的try-catch异常处理?

Java 如何解决我的try-catch异常处理?,java,exception,try-catch,Java,Exception,Try Catch,我的try-catch异常出现问题。实际上,它所做的是提示用户输入一个文本文件的名称,比如Robot.txt,但是如果说该文件不存在,我必须确保应用程序重新向用户输入文件名。希望你们能理解我仍然是一个新手,所以请随时提供建议或建议,我的编码等。干杯 主要方法类: import java.io.*; import java.util.Scanner; import java.util.Vector; class TestVector3 { public static void main(Str

我的
try-catch异常出现问题。实际上,它所做的是提示用户输入一个文本文件的名称,比如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();
}
}

您可以调用
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");
  }
这确实是一个错误,因为您假设检查文件存在的唯一方法是捕获
FileNotFoundException
(因此询问try-catch异常处理),而其他方法可以帮助您以优雅的方式避免try-catch习惯用法

要检查给定路径中是否存在文件,只需使用该方法即可。另请参阅验证目标文件对象性质的方法和/或方法


编辑:如raphw所述,此解决方案最好在简单场景中使用,因为在文件存在性检查期间发生并发文件删除的情况下,它可能导致竞争条件。有关处理更复杂场景的信息,请参见his。

当您声明自己是初学者时,让我们先看看代码的相关部分,以确保我们讨论的内容相同:

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
检查文件是否存在。但是,如果您在检查文件是否存在后读取该文件,则该文件可能会同时被删除,从而导致赛车状态

回答您的评论:在Java(或几乎任何编程语言)中,您可以使用内联表达式。这意味着不要像中那样在两个不同的语句中调用两个方法

Foo foo = method1();
Bar bar = method2(foo);
你只要打个电话就可以了

Bar bar = method2(method1());
这样,您就可以为自己节省一些空间(如果代码变长,这一点会变得越来越重要),因为您不需要在代码中的任何其他位置保存在
foo
中的值。类似地,您可以从

进入


由于
文件
变量仅在创建
扫描仪时读取

请勿使用try-catch,而是将其添加为您的功能。异常通常用于运行时错误处理,而不是逻辑构建

检查文件是否存在于给定位置

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循环。

尝试将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!");
    }
}

接下来,您可以考虑将文件创建部分移动到单独的方法中,以便代码更干净。

可能重复:@m4rtin no它与此无关question@RuchiraGayanRanaweera大概问题没有明确说明,所以我可能做出了错误的假设。@m4rtin如果您仍有疑问,您可以仔细阅读问题,然后发表评论并获得澄清。@RuchiraGayanRanaweera嗨,Ruchira,非常感谢您帮助我向Martin澄清我的问题。。)OP不希望逻辑检查文件是否存在。他想给出一条消息,并要求用户在第一次尝试出错时重新输入文件名。仔细阅读问题。请告诉我在何种情况下用户必须重新输入文件名?:)如果第一次尝试包含错误的文件名,则要求用户重新输入文件名。仔细阅读问题。没错,你如何检查文件名是否错误?@RuchiraGayanRanaweera OP不是问如何使用递归,而是问如何重复文件名的提示。正如我在对你答案的评论中所解释的,递归对于解决这个问题来说是一个糟糕的解决方案。另外,正如我在对另一个答案的评论中所解释的,显式检查是有缺陷的。不要对此使用递归!这样,如果用户多次输入错误的文件名,则可能会出现
堆栈溢出错误。用户甚至可以在查找VuNerability时故意使应用程序崩溃。@raphw您认为有多少次?你真的认为有人想输入接近百万的错误文件名吗?作为一名程序员,我会为自己编写一个软件。@RuchiraGayanRanaweera哦,嘿,我在这里学到了一些关于
main(args)
的新知识,我不知道我们实际上可以调用我们的主方法干杯!落选选民:我想这是报复性的落选。否则,请澄清您的批评。哦,嗨,嗨,非常感谢您指导我进行erm。我可以问一下这行代码吗
fileInput=new Scanner(new File(userInput.nextLine())不过我不太明白。你为什么要把单词newfile放在这行?我能研究一下吗?干杯D无论如何都感谢您的帮助,但我正在自学过去的功课,上面说我必须使用
try catch exception
:D
fileInput = new Scanner(new File(userInput.nextLine()));
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());

 }
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!");
    }
}