【发布时间】:2015-04-15 16:31:07
【问题描述】:
我想从文件的内容中创建一个字符串。根据this answer我是这样操作的:
private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(stringTemplatePath));
return new String(encoded, "UTF-8");
}
(据我了解,这是一条新的 NIO2 API 路径,它是 Java 7 的一部分。)
stringTemplatePath 参数是文件名(“template.html”)。我检查了这个文件的位置。它在类路径中:../classes/template.html
调用此函数后出现异常:
java.nio.file.NoSuchFileException: template.html
也许我以错误的方式发送文件名参数?我尝试发送此修改:"file:///template.html" 和 "classpath:template.html",但没有帮助。
我也试过这段代码:
private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
File file = new File(stringTemplatePath);
String absolutePath = file.getAbsolutePath();
byte[] encoded = Files.readAllBytes(Paths.get(absolutePath));
return new String(encoded, "UTF-8");
}
我调用了这个函数我得到了以下异常:
java.nio.file.NoSuchFileException: /opt/repo/versions/8.0.9/temp/template.html
所以,类路径中的文件,因为 new File(stringTemplatePath) 可以创建一个文件。但是这个文件的路径很奇怪(/opt/repo/versions/8.0.9/temp/template.html)。我使用 Jelastic 作为主机(环境:Java 8、Tomcat 8),如果是米特的话。
更新:最终工作解决方案:
private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream(stringTemplatePath);
return IOUtils.toString(inputStream, "UTF-8");
}
IOUtils 是来自 Apache IO Commons 的 util 类。
重要提示:
如果我只是从 class 调用 .getResourceAsStream(...),将找不到资源文件并且方法将返回 null:
MyClass.class.getResourceAsStream(stringTemplatePath);
所以,我在调用 .getResourceAsStream(...) 之前调用了 .getClassLoader() 并且效果很好:
MyClass.class.getClassLoader().getResourceAsStream(stringTemplatePath);
【问题讨论】:
-
不要使用路径(或文件;在 2015 年根本不要使用文件)访问文件系统上的资源!有
.getResourceAsStream() -
@fge 谢谢!使用 .getResourceAsStream() 一切正常!你会发布你的答案吗?
标签: java io classpath jelastic nio2