【发布时间】:2020-08-14 04:10:44
【问题描述】:
我发现这个文件存在于显示的 url 中,但仍然得到 NoSuchFileException。 尝试了很多方法,但路径返回始终相同,但无法读取文件。会怎样?它在那里但不在那里?为什么?
public void readFile() throws IOException {
String fileName = "domain.txt";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
//File is found
System.out.println("File Found : " + file.exists());
//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
}
【问题讨论】:
-
你有没有尝试过这样的事情:stackoverflow.com/questions/3888226/…?而且,顺便说一句,您永远不应该将您的代码作为图片发布。将代码和输出粘贴到问题本身,以便我们复制它。
-
资源不是文件。您需要使用
Class.getResource()和朋友,而不是文件。请勿在此处发布文字图片。发布文本。 -
@MarquisofLorne 抱歉,我已经编辑过了。但是当我使用 Class classer = getClass(); URL url = class.getResource("domain.txt");我得到空
-
不要调用
getFile(),或者创建File,或者其他的。ClassLoader.getResource()返回一个URL:直接从中获取输入流。