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.
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.
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.
Yes. The FileNotFoundException is inherited from the IOException. Exception's subclasses have to be caught first. Save this answer.
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");
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With