用eclipse找不到文件

问题描述 投票:0回答:4

好吧,我浏览了这个网站和其他一些网站,寻找这个问题的答案,并尝试了所有的建议。什么都不起作用,它不断抛出

File not found exception

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());
}

文本文件与我正在工作的目录位于同一目录中,并且我双重确保在代码中正确命名它。请帮忙。

java eclipse file-io fileinputstream
4个回答
0
投票

尝试将您的文件放在这里。

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

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

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

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
投票

您是否启用了eclipse控制台中的输入?以前从 eclipse 控制台使用时,扫描仪给我带来了一些问题..

enter image description here

来源:https://stackoverflow.com/a/22471175/441907


0
投票

如果文件放在 src 下,请尝试从类路径加载

Scanner scanner=new Scanner(YourClass.class.getResourceAsStream("/package/...pathtofile");
© www.soinside.com 2019 - 2024. All rights reserved.