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

I use Eclipse to compile and run my java codes.

Here is the 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 created a .txt file in the same folder in my project.

+6
source share
4 answers

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

So, if your project folder is MyProject , the folder structure (not full) should look like this: -

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

It should not be a folder under src .


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

 new File("src/file.txt"); 
+19
source

Try passing the full path to the file, say:

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

Or if you are in the windows:

 new File("C:/Users/mogli/docs/file.txt") 
+5
source

Approach @rohit Jains approach or specify an absolute path for the file :

  Scanner KB = new Scanner(new File("C:/JsfProjects/Project/file1.txt")); while (KB.hasNext()) { String line = KB.nextLine(); System.out.println(line); } 
+2
source

On Windows, try giving a real way like this

 "C:\\Users\\mogli\\docs\\file.txt" 

It worked for me.

+1
source

All Articles