2014-04-13 76 views
-1

自從我與文件混淆了很長一段時間。我正在嘗試在eclipse中創建一個txt文件,並在此代碼中使用它。處理獲取文件名,查找文件,掃描它的代碼是:從用戶輸入中掃描文件

System.out.println("Input from a file"); 
System.out.print("Enter file name: "); 
String str = expression.nextLine(); 
int i = 0; 
File file = new File(str); 
Scanner fScan = new Scanner(file); 

我得到的是FileNotFoundExceptions。我的文件與我的所有課程都在同一個文件夾中,我無法在網上找到真正有用的答案。

因此,如果有人能指出我要去的地方錯了,這將是巨大的:)

+0

請分享項目結構。 – Braj

+0

我相信你的輸入文件路徑是錯誤的。因爲,我沒有問題 – sancho21

回答

0

所有的你有應該是一個嘗試{}內,外有一個catch代碼行,那會趕上該FileNotFoundException異常,例如,

Try{ 
/*your code here*/ 
// but try this 
Scanner scannerName = new Scanner("FileName.<extension>"); //extension being .txt, etc 
String str; 
while(scannerName.hasNext());{ 
str = scannerName.nextLine(); 
/*work with str here*/ 
} 
Catch(FileNotFoundException e){ 
System.out.println("File not found"); 
} 
0

如果在同一個包哪裏是類文件的文件,那麼你可以試試這個也:

Scanner fScan = new Scanner(this.getClass().getResourceAsStream("abc.txt")); 
//do not forget to close the Scanner in the end 
fScan.close() 

展望從資源文件夾

File file = new File("resources/abc.txt"); 

這裏文件abc.txt是項目結構

enter image description here

0

你確定該文件是在根文件夾?默認的工作目錄是項目目錄。

如果您確信您的文件是有那麼它的無論是你的錯打字的時候你的文件的名稱,或somethine其他正在發生的事情,來弄明白,我建議你嘗試以下3個試驗:

當你鍵入文件名有沒有搞錯

1 - 確保

2,儘量把文件的完整路徑,看看現在它會發現它

3,嘗試把儘可能名稱有點像

新文件(「src/pa/Yourinput.txt」)。