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

Jel*_*rns 4 java spring classpath

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

Files.readAllBytes(new ClassPathResource("project.txt").getFile().toPath())
Run Code Online (Sandbox Code Playgroud)

project.txt当我处于战争状态时,这工作得很好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
Run Code Online (Sandbox Code Playgroud)

我仍在 Tomcat 容器中执行 WAR。

我怎样才能解决这个问题?

San*_*ose 5

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

示例代码:

ClassLoader CLDR = this.getClass().getClassLoader();
InputStream inputStream = CLDR.getResourceAsStream(filePath);
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 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);
Run Code Online (Sandbox Code Playgroud)