Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in thread "main" java.io.FileNotFoundException: Error

I am using Eclipse to compile and run my java codes.

Here is Error I am getting.

Exception in thread "main" java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at helloworld.main(helloworld.java:9)

Here is my Code

import java.io.File;
import java.io.IOException;
import java.util.Scanner;


public class helloworld {

    public static void main(String[] args) throws IOException {
        Scanner KB = new Scanner(new File("file.txt"));
        while (KB.hasNext()) {
            String line = KB.nextLine();
            System.out.println(line);
        }

    }
}

File.txt
I have created file.txt in same folder in my project.

like image 469
Mowgli Avatar asked Nov 27 '12 20:11

Mowgli


People also ask

Can we handle FileNotFoundException?

FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn't occur.

Does IOException catch FileNotFoundException?

When you catch IOException you also catch FileNotFoundException. It is still possible to handle the two exceptions with each their own catch-block as shown earlier, even if only the superclass is declared thrown.

Does it matter in what order Catch statements for FileNotFoundException and IOException are written?

Yes. The FileNotFoundException is inherited from the IOException. Exception's subclasses have to be caught first. Save this answer.


2 Answers

Your file should directly be under the project folder, and not inside any other sub-folder.

So, if your project folder is MyProject, it's folder structure(not complete though) should be like: -

MyProject +- src +
          |      |
          |      +-- Your source file
          +- file.txt

It should not be under src folder.


Or, you can give the following path relative to the project folder to search for file in the src folder: -

new File("src/file.txt");
like image 127
Rohit Jain Avatar answered Oct 18 '22 14:10

Rohit Jain


Try passing the complete path to the file, say:

new File("/usr/home/mogli/file.txt")

Or if you're in windows:

new File("C:/Users/mogli/docs/file.txt")
like image 24
Óscar López Avatar answered Oct 18 '22 14:10

Óscar López