简体   繁体   English

Java:从文件读取时,扫描仪不接受try-catch类错误

[英]Java: Scanner not accepting try-catch class error when reading from file

At Java 8 documentation, it is written that the constructor from Scanner which receives a File Source as parameter throws a FileNotFoundException . 在Java 8文档中,据写道,来自Scanner的构造函数接收到File Source作为参数,抛出了FileNotFoundException But take a look at the following code: 但是,请看以下代码:

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

When I run it, I get something like: 当我运行它时,我得到如下信息:

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

Same happens with IOException . IOException发生同样的情况。 The curious is that, if I throw away the try-catch part, the code compiles. 奇怪的是,如果我丢掉try-catch部分,代码就会编译。

What is wrong here? 怎么了

Scanner can also scan a String. 扫描程序还可以扫描字符串。 To see what I mean, try: 要了解我的意思,请尝试:

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

It will print Rede.txt . 它将打印Rede.txt

Some other classes (like eg FileInputStream) will take a String path, but Scanner doesn't. 其他一些类(例如FileInputStream)将采用String路径,但Scanner则不采用。 If you want to use a file, you need to actually pass it a File: 如果要使用文件,则需要实际将文件传递给它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM