【问题标题】:java:40: error: exception FileNotFoundException is never thrown in body of corresponding try statementjava:40: 错误:异常 FileNotFoundException 永远不会在相应的 try 语句的主体中抛出
【发布时间】:2021-12-21 17:30:59
【问题描述】:

我正在尝试使用 Java 打开一个文件。如果操作不成功,我的程序应该输出The file was not found, please download file with name DateTemp.csv.。这是我的代码:

File myFile = new File("DateTemp.csv");                     //File Name
Scanner inputFile = new Scanner(myFile);                    //scanner to input file name
try {
    //Try to display one too many array elements.
    myFile = new File("DateTemp.csv");
    for (int i = 0; i <= templow.length; i++);
    for (int i = 0; i <= temphigh.length; i++);
    //System.out.println(temphigh[i]);
    //System.out.println(templow[i]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid array index exceeds Array Size.");                  //catch block to declare the array index was too large
} catch (FileNotFoundException e) {
    System.out.println("The File was not Found, please download file with name DateTemp.csv");
    System.exit(1);
}

【问题讨论】:

  • 你不需要做第二个“myFile = new File...”。
  • 您可能会遇到错误,因为您的文件 DateTemp.csv 的路径是错误的。

标签: java filenotfoundexception


【解决方案1】:

Scanner inputFile = new Scanner(myFile); 代码放在try 块内

【讨论】:

  • 移动代码的位置有效,但在代码下方我收到错误错误:变量 inputFile 已在方法 main(String[]) 中定义 Scanner inputFile = new Scanner(myFile) ;
  • 错误应该说明一切。您已经在方法中编写了Scanner inputFile = ...,现在您正在尝试再次定义它。删除该行或将第二行更改为仅 inputFile = ... 没有 Scanner 部分以重新定义变量
猜你喜欢
  • 2017-07-01
  • 2011-05-18
  • 2015-05-29
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多