【问题标题】:Cann't get file from classpath (using NIO2)无法从类路径获取文件(使用 NIO2)
【发布时间】: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


【解决方案1】:

您不应尝试以 Paths 的身份访问类路径中的资源。

虽然当您的项目位于您的 IDE 设置中时这很可能会起作用,但一旦您的项目被打包为 jar,它就不会;然后即使使用Path 也无法访问它们(即使您可以打开 zip 文件,因此也可以打开 jars,如 FileSystems)。

请改用专用方法,从.getResourceAsStream()开始:

final InputStream in = MyClass.class.getResourceAsStream("/path/to/resource");

请注意,您需要检查该方法的返回码是否为null(这是在类路径中找不到资源时返回的内容)。

【讨论】:

  • 不幸的是 MyClass.class.getResourceAsStream(...); 对我不起作用。在我的情况下,以下代码有效:MyClass.class.getClassLoader().getResourceAsStream(...);再次感谢您的帮助!
【解决方案2】:

如果文件确实是类路径的一部分,您应该使用: ClassName.class.getResourceAsStream("/file name") 这返回 InputStraem

ClassName.class.getResource("/file name") 这个返回网址

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 2010-10-14
    • 2013-08-28
    相关资源
    最近更新 更多