我一直在网上寻找解决这个看似简单问题的方法,但我总是遇到FileNotFoundException
。我在Eclipse Oxygen上使用Java 8,无法从绝对路径或相对路径中检索我的txt
文件。正如在其他SO answers中建议的那样,我得到了当前目录的路径,我想这是从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"))
< / p>
我甚至尝试过绝对路径:Scanner input = new Scanner(new File("E://eclipse-java-oxygen-R-win32//HashMap//free.txt"));
我在下面提供了我的free.txt文件位置的屏幕截图。
答案 0 :(得分:1)
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();
}
至少这应该告诉你更多关于错误的信息并为你做调试。
答案 1 :(得分:0)
我不知道你的文件在哪里,但我认为这正是你要找的。我有一个名为test.json的文件
String jsonString = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("test.json").toURI())));