如何解决从资源Java读取文件
我发现此文件存在于所显示的url中,但仍然得到NoSuchFileException。 尝试了多种方法,但是路径始终返回相同,但无法读取文件。会怎么样?它在那里但不在那里?为什么请PLZ?
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);
}
解决方法
使用ClassLoader时,必须使用绝对路径
public void readFile() throws IOException {
// Must use absolute path here,so start with a slash
String fileName = "/domain.txt";
// Use InputStream instead of File
InputStream input = ClassLoader.getSystemResourceAsStream(filename);
BufferedReader bf = new BufferedReader(new InputStreamReader(input));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bf.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
System.out.println(content);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。