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.
Solution 1:
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");
Solution 2:
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")
Solution 3:
Either follow @rohit Jains approach or give the absolute path for your file like:
Scanner KB = new Scanner(new File("C:/JsfProjects/Project/file1.txt"));
while (KB.hasNext()) {
String line = KB.nextLine();
System.out.println(line);
}