FileNotFoundException when using BufferedReader on a file

15,143

Solution 1

The exception trace is saying that your code...

BufferedReader infixLines = new BufferedReader ( new FileReader ( "input.infix" ));

Could possibly throw a FileNotFoundException or an IOException if the file doesn't exist, so it wants you to do something to handle this possibility.

The simplest way is to wrap your file-reading code in a try-catch block like this...

try {
    BufferedReader infixLines = new BufferedReader ( new FileReader ( "input.infix" ));
    // other reading code here
}
catch (FileNotFoundException e){
    System.out.println(e);
}
catch (IOException e){
    System.out.println(e);
}

The exception isn't saying that the file can't be found, it is just saying that if the file doesn't exist, what is your code going to do to handle the situation.

Ultimately in the catch block you would want to do something more than just System.out.println(). For example, in a GUI program, you might show a popup message to tell the user that the file doesn't exist.

Solution 2

this line

BufferedReader infixLines = new BufferedReader (new FileReader("input.infix"));

searches for File: input.infix, if it not found then it will return FileNotFoundException exception. Make sure that input.infix resides in the directory same with the java file.

Solution 3

Its a compilation error, not a runtime exception.

You need to wrap your File related calls within a try-catch block and handle FileNotFounceException and IOException

Share:
15,143
Wuzseen
Author by

Wuzseen

Updated on June 14, 2022

Comments

  • Wuzseen
    Wuzseen almost 2 years

    I'm very confused on getting basic file reading to work with Java. Lots of mixed signals.

    I've tried it a couple different ways and I consistently get a not found exception each time. I've checked with a file object set to the current path to print the current directory and I am indeed in the directory the file I'm trying to open is in. The permissions are set so everyone can read. I'm not sure what is going on:

    BufferedReader infixLines = new BufferedReader ( new FileReader ( "input.infix" ));
    

    This is the line that throws the error, consequently each consecutive line using infixLines also throws an error.

    I've tried it using FileInputStream as well and get the same kind of error.

    That being said simply doing

    File file = new File("input.infix");
    if ( file.exists() )
        System.out.println( "Exists" );
    

    DOES work.

    Very confused.

    EDIT: (Stacktrace?)

    ParseInfix.java:13: unreported exception java.io.FileNotFoundException; must be
                BufferedReader infixLines = new BufferedReader(new FileReader (n
                                                               ^
    ParseInfix.java:15: unreported exception java.io.IOException; must be caught or
                while ( ( line = infixLines.readLine()) != null )