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);
}
添加回答
舉報