Resolving IOException, FileNotFoundException when using FileReader

孤街浪徒 提交于 2019-12-04 20:18:29

Add throws FileNotFoundException, IOException in the header of your method. It looks like just throwing the IOException will solve your problem, but incorporating both will allow you to tell if there was a problem with the file's existence or if something else went wrong (see catch statements below).

i.e.

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

Alternately, if you'd like to catch a specific exception and do something with it:

try {
    BufferedReader buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
    // Do something with 'ex'
} catch (IOException ex2) {
    // Do something with 'ex2'
}

Update to resolve the updated issue: This is just a simple scope problem which can be solved by declaring the BufferedReader outside of the try statement.

BufferedReader buffread = null;
try {
    buffread = new BufferedReader (new FileReader("file.txt"));
} catch (FileNotFoundException ex) {
        ...

You have to add throws statement into the signature of method main or wrap code in

try {
    ...
} catch (FileNotFoundException e) {
    ...
}
Rafi Kamal

Your code can throw FileNotFoundException or IOException which is Checked Exception. You need to surround your code in a try-catch block or add a throws declaration in your main function.

The BufferReader can throw an exception if the file cannot be found or opened correctly.

This error message is telling you that you need to handle this exception. You can wrap the line where you create the BufferReader in a try/catch block. This will handle the case an IOException is thrown and print out the stack trace.

public static void main(String[] args) { 
    ParseFileName  superParse = new ParseFileName();  
    BufferedReader buffread;
    try
    {
        buffread= new BufferedReader (new FileReader("file.txt"));
    }
    catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }

    String line;
    while ((line = buffread.readLine())!= null) {
        String fileName = superParse.getName(line);
        System.out.println("\n" + line + "  =>  " + fileName);
    }
    buffread.close();
}

Another option is to add "throws IOException" to your method header.

public static void main(String[] args) throws IOException {
    //...
}

This tells the compiler and callers of your method that you are choosing to not handle this exception and there is a chance it will be thrown.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!