2012-11-27 54 views
6

我使用Eclipse来编译和运行我的java代码。线程“主”异常java.io.FileNotFoundException:错误

这是我得到的错误。

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) 

这里是我的代码

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
我已经在我的项目创造了同一个文件夹file.txt的。

+0

您的文件是否直接在您的项目文件夹下? –

+0

它在SCR下,我也把一个放在bin下面,因为scr没有工作。 – Mowgli

+1

尝试打印'新的文件(“file.txt”)。exists()'是否产生'true'?如果没有,尝试打印'新的文件(“file.txt”)。getAbsoluteFile()'这是你所期望的? – amit

回答

19

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

所以,如果你的项目文件夹是MyProject,它的文件夹结构(尽管未完成)应该是这样的: -

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

它不应该是文件夹。


或者,你可以给以下路径相对于项目文件夹中搜索文件src folder: -

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

这个为我工作。 +来@Rohit –

+0

啊辉煌。没有猜测。 – gbhall

5

尝试将完整的文件路径,说:

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

或者如果你在Windows中:

new File("C:/Users/mogli/docs/file.txt") 
2

要么跟随@rohit耆那教的办法还是给绝对路径文件,如:

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

+1考虑使用正斜杠'/'而不是反斜杠\。 –

+0

@ Eng.Fouad谢谢,我会更新答案:) – PermGenError

1

在Windows尝试给这样

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

它为我真正的路径。

相关问题