简体   繁体   中英

FileReader can't read file

I got an error "Unhandled Exception: java.io.FileNotFoundException, though I'm sure about the file path, need some help

public static void main(String[] args) {

    BufferedReader reader = null;
    int total =0;
    reader = new BufferedReader(new FileReader("C:\\Numbers.txt"));
}

Your code lacks of Exception handling. You are sure about the file presence, but the program is not, at compilation time. Just declare it on main method:

public static void main(String[] args) throws FileNotFoundException {

}

Or use a try-catch block:

try {
    reader = new BufferedReader(new FileReader("C:\\Numbers.txt"));
} catch (IOException e) {
     e.printStackTrace(); 
}

could you please try with

reader = new BufferedReader(new FileReader("C:/Numbers.txt"));

This is a compile-time error. FileNotFoundException is a checked exception which means that you have to state what Java should do if it is encountered. There may be a case where the file may not be present so Java asking you to handle that scenario either by try/catch block or throws keyword

To make your code work jus add as below:

public static void main(String args[]) throws FileNotFoundException 
{

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