我使用以下代码从类路径读取文件:
Files.readAllBytes(new ClassPathResource("project.txt").getFile().toPath())
当 project.txt
时,这工作得很好。位于src/main/resources
我的 war 。现在我重构了代码并将某些代码移至 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);
关于java - 如何从 JAR 中的类路径读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50172197/