3 回答

TA贡献1829条经验 获得超7个赞
resource.getFile()期望资源本身在文件系统上可用,即不能嵌套在jar文件中。这就是为什么当您在STS中运行应用程序时它可以工作,但是一旦您构建了应用程序并从可执行jar中运行它后,它就无法工作。建议不要使用getFile()来访问资源的内容getInputStream()。这样一来,无论资源位于何处,您都可以阅读其内容。

TA贡献1895条经验 获得超3个赞
如果您使用的是Spring框架,那么使用Spring框架的读ClassPathResource入String是非常简单的FileCopyUtils:
String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException", e);
}

TA贡献1802条经验 获得超5个赞
如果要使用文件:
ClassPathResource classPathResource = new ClassPathResource("static/something.txt");
InputStream inputStream = classPathResource.getInputStream();
File somethingFile = File.createTempFile("test", ".txt");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
添加回答
举报