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

Mowgli picture Mowgli · Nov 27, 2012 · Viewed 58.6k times · Source

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.

Answer

Rohit Jain picture Rohit Jain · Nov 27, 2012

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");