2014-10-10 50 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");