我想从文件的内容创建一个字符串。根据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),如果是 metter 的话。
<小时/>更新:最终工作解决方案:
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);
最佳答案
您不应该尝试将类路径中的资源作为 Path
访问。
虽然当您的项目位于 IDE 设置中时这很可能会起作用,但当您的项目打包为 jar 时它就不会起作用;那么甚至无法使用 Path
访问它们(即使您可以打开 zip 文件,因此 jars,作为 FileSystem
s)。
使用专用方法来执行此操作,从 .getResourceAsStream() 开始
:
final InputStream in = MyClass.class.getResourceAsStream("/path/to/resource");
请注意,您需要检查该方法的返回代码是否为null
(如果在类路径中找不到资源,则返回该代码)。
关于java - 无法从类路径获取文件(使用 NIO2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655811/