2012-11-27 82 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" 

它爲我真正的路徑。

相關問題