2014-10-10 52 views
0

好吧,我搜索了這個網站和其他一些人尋找這個問題的答案並嘗試了所有的建議。沒有什麼工作,它不斷拋出File not found exception使用eclipse無法找到文件

File inFile = new File("PhoneRecords.txt"); 
String path = inFile.getAbsolutePath(); 
try { 
    System.setIn(new FileInputStream(path)); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 
Scanner sc = new Scanner(System.in); 

之後它嘗試在下面的方法中使用掃描儀。

public static PhoneCall readNextPhoneCall(Scanner sc){ 
    return new PhoneCall (sc.nextDouble(), sc.nextInt()); 
} 

的文本文件是在我在我的工作同一個目錄和我雙確信,我在我的代碼正確命名它。請幫忙。

+0

使用Eclipse調試器。設置一個斷點並遍歷代碼,以查看哪些行爲無法滿足您對發生的事情的假設。 – duffymo 2014-10-10 12:53:34

+0

可能的[重複](http://stackoverflow.com/q/19871955/2587435) – 2014-10-10 12:55:12

+0

將它保持在與source/bin目錄相同的級別,然後嘗試。 – TheLostMind 2014-10-10 12:56:24

回答

0

用相對路徑創建File總是有風險。要麼使用絕對路徑(如/ my/absolute/path),要麼使用其他方法來獲取文件。

另外,爲什麼不使用此構造:Scanner(File source)

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)

或者更好的,用這一個:Scanner(InputStream source)

然後,使用的getResourceAsStream正確檢索您的文件

InputStream is = getClass().getClassLoader().getResourceAsStream("PhoneRecords.txt"); 
Scanner sc = new Scanner(is); 
0

試着把你的文件放在這裏。

--->bin 
--->src 
--->PhoneRecords.txt 

或指定文件的位置。例如,

String path = "C:\\MyFiles\\PhoneRecords.txt"; 
File inFile = new File(path); 
0

如果文件被放在src下試裝車的類路徑

Scanner scanner=new Scanner(YourClass.class.getResourceAsStream("/package/...pathtofile");