【问题标题】:Java: Scanner not accepting try-catch class error when reading from fileJava:从文件读取时扫描程序不接受 try-catch 类错误
【发布时间】:2015-05-22 00:42:04
【问题描述】:

在 Java 8 文档中,从 Scanner 接收文件源作为参数的构造函数会抛出 FileNotFoundException。 但是看看下面的代码:

  try{
            sc = new Scanner("Rede.txt");      //This archive already exists
        }
        catch(FileNotFoundException f){
            f.printStackTrace;
        }
        finally{
            sc.close();
        }

当我运行它时,我会得到类似的东西:

error:exception FileNotFoundException is never thrown in body of corresponding try statement
              catch(FileNotFoundException f){

IOException 也是如此。奇怪的是,如果我扔掉 try-catch 部分,代码就会编译。

这里有什么问题?

【问题讨论】:

    标签: java file exception try-catch java.util.scanner


    【解决方案1】:

    扫描器也可以扫描字符串。要了解我的意思,请尝试:

    System.out.println( new Scanner("Rede.txt").next() );
    

    它将打印Rede.txt

    其他一些类(例如 FileInputStream)将采用 String 路径,但 Scanner 不会。如果要使用文件,则需要实际传递一个文件:

    sc = new Scanner(new File("Rede.txt"));
    

    【讨论】:

    • 谢谢,这很有帮助!
    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多