Exception in thread “main” java.io.FileNotFoundException: Error

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 11:32:52

问题


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.


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



回答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")



回答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);
            }



回答4:


In Windows try giving real path like this

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

It worked for me.



来源:https://stackoverflow.com/questions/13592325/exception-in-thread-main-java-io-filenotfoundexception-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!