【问题标题】:How can I read a file from the classpath in a JAR? [duplicate]如何从 JAR 中的类路径读取文件? [复制]
【发布时间】:2018-10-14 18:43:33
【问题描述】:

我正在使用以下代码从类路径中读取文件:

Files.readAllBytes(new ClassPathResource("project.txt").getFile().toPath())

project.txt 在我的 WAR 的 src/main/resources 中时,这工作正常。现在我重构了代码并将某些代码移到了 JAR 中。这个新的 JAR 现在包括 src/main/resources/project.txt 和上面的代码。现在读取文件时出现以下异常:

java.io.FileNotFoundException: class path resource [project.txt]
cannot be resolved to absolute file path because it does
not reside in the file system:
jar:file:/usr/local/tomcat/webapps/ROOT/WEB-INF/lib/viewer-1.0.0-SNAPSHOT.jar!/project.txt

我仍在 Tomcat 容器中执行 WAR。

我该如何解决这个问题?

【问题讨论】:

    标签: java spring classpath


    【解决方案1】:

    您不能像从资源中引用文件那样从 jar 中引用文件。由于文件打包在 jar 中,因此您需要将其作为资源读取。 您必须使用类加载器将文件作为资源读取。

    示例代码:

    ClassLoader CLDR = this.getClass().getClassLoader();
    InputStream inputStream = CLDR.getResourceAsStream(filePath);
    

    如果您使用的是 java 8 及更高版本,那么您可以使用以下代码使用 nio 来读取您的文件:

    final Path path = Paths.get(Main.class.getResource(fileName).toURI());
    final byte[] bytes = Files.readAllBytes(path);
    String fileContent = new String(bytes, CHARSET_ASCII);
    

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多