无法使用相对路径检索文件
Cant retrieve file using relative path
我一直在网上搜索这个看似简单的问题的解决方案,但我总是 运行 变成 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"))
我什至尝试了绝对路径:Scanner input = new Scanner(new File("E://eclipse-java-oxygen-R-win32//HashMap//free.txt"));
我在下面附上了我的 free.txt 文件位置的屏幕截图。
非常感谢您的帮助。
我不知道你的文件在哪里,但我想这就是你要找的。我有一个名为 test.json
的文件
String jsonString = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("test.json").toURI())));
嗯,让我们试着把事情分开,这样我们才能知道到底是什么问题。您还可以尝试通过打印文件异常的确切错误来获取更明确的错误消息。像这样:
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();
}
至少这应该告诉您更多有关错误的信息并为您进行调试。
我一直在网上搜索这个看似简单的问题的解决方案,但我总是 运行 变成 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"))
我什至尝试了绝对路径:Scanner input = new Scanner(new File("E://eclipse-java-oxygen-R-win32//HashMap//free.txt"));
我在下面附上了我的 free.txt 文件位置的屏幕截图。
我不知道你的文件在哪里,但我想这就是你要找的。我有一个名为 test.json
的文件String jsonString = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("test.json").toURI())));
嗯,让我们试着把事情分开,这样我们才能知道到底是什么问题。您还可以尝试通过打印文件异常的确切错误来获取更明确的错误消息。像这样:
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();
}
至少这应该告诉您更多有关错误的信息并为您进行调试。