我一直在网上搜寻该看似简单的问题的解决方案,但我总是遇到FileNotFoundException
。我在Eclipse Oxygen上使用Java 8,无法txt
从绝对路径或相对路径检索文件。正如其他SO答案中所建议的那样,我获得了当前目录的路径,我想这是从中加载txt文件的位置:
Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
这显示我的目录为 E:\eclipse-java-oxygen-R-win32\HashMap
但是,当我将txt文件添加到该项目目录(包含src
,bin
目录)时,在我编写该文件时仍找不到该文件:Scanner input = new Scanner(new File("free.txt"))
我什至尝试了绝对路径: Scanner input = new Scanner(new File("E://eclipse-java-oxygen-R-win32//HashMap//free.txt"));
我在下面提供了我的free.txt文件位置的屏幕截图。
嗯,让我们尝试将事情分解,以便我们确切地知道问题所在。您还可以尝试通过打印File Exception的确切错误来获得更明确的错误消息。像这样:
catch (IOException e) {
System.out.println("IOException caught -- ");
System.out.println(e.getMessage());
}
但是,进一步。您的路线:Scanner input = new Scanner(new File("free.txt"))
可以拆分。
试试这个:
String file_name="free.txt";
File file_input = new File(file_name);
if (!file_input.exists())
abort("FileInput: no such source file: " + file_name);
if (!_file_input.isFile())
abort("FileInput: can't open a directory: " + file_name);
if (!file_input.canRead())
abort("FileInput: source file is unreadable: " + file_name);
然后跑
try {
`Scanner input = new Scanner(file_input)`
catch (FileNotFoundException e) {
e.printStackTrace();
}
至少这应该告诉您更多有关错误的信息,并为您进行调试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句