线程“主”中的异常java.io.FileNotFoundException:错误 [英] Exception in thread "main" java.io.FileNotFoundException: Error

查看:527
本文介绍了线程“主”中的异常java.io.FileNotFoundException:错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在收到错误。

 线程main中的异常java.io.FileNotFoundException:file.txt(系统找不到指定的文件)
在java.io .FileInputStream.open(Native Method)
在java.io.FileInputStream。< init>(未知源)
在java.util.Scanner。< init>(未知来源)
在helloworld.main(helloworld.java:9)

这是我的代码

  import java.io.File; 
import java.io.IOException;
import java.util.Scanner;


public class helloworld {

public static void main(String [] args)throws IOException {
扫描程序KB =新扫描程序file.txt的));
while(KB.hasNext()){
String line = KB.nextLine();
System.out.println(line);
}

}
}

File.txt

我在项目中的同一个文件夹中创建了file.txt。

解决方案

您的文件应该直接位于项目文件夹下,而不在任何其他子文件夹中。



所以,如果你的项目文件夹是 MyProject ,它的文件夹结构(不完整)应该是: -

  MyProject +  -  src + 
| |
| + - 您的源文件
+ - file.txt

不应该是在src 文件夹下。






或者,您可以给出以下路径相对到项目文件夹以在 src文件夹中搜索文件: -

 新建文件(src / file.txt); 


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.

解决方案

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

这篇关于线程“主”中的异常java.io.FileNotFoundException:错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆