简体   繁体   中英

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 . 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 . The curious is that, if I throw away the try-catch part, the code compiles.

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 .

Some other classes (like eg FileInputStream) will take a String path, but Scanner doesn't. If you want to use a file, you need to actually pass it a File:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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