如何从 JAR 中的类路径读取文件?

How can I read a file from the classpath in a JAR?

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

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。

我该如何解决这个问题?

您不能像从资源中那样引用 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);