背景:
springboot本地加载静态文件访问正常,打jar放到linux服务器报ileNotFoundException class path resource [static/taobao.dict] cannot be resolved to absolute file path because it does not reside in the file system: jar ..类似错误
原因:
通过
ResourceUtils.getFile("classpath:static/taobao.dict");//前缀有classpath
或
ClassPathResource resource = new ClassPathResource("static/taobao.dict");//前缀无classpath
InputStream inputStream = resource.getInputStream();
File file = resource.getFile();
只能获取类文件下文件,无法从jar包获取
解决方法:
通过ClassPathResource.getInputStream()获取
如:此处我将jieba切词词典作为静态文件放进内存读取
ClassPathResource resource = new ClassPathResource(“static/taobao.dict”);
InputStream inputStream = resource.getInputStream();
File taobaoDictFile = File.createTempFile("taobao", ".dict");
FileUtils.copyInputStreamToFile(inputStream, taobaoDictFile);
WordDictionary.getInstance().loadUserDict(taobaoDictFile.toPath(), StandardCharsets.UTF_8);
参考资料:
https://www.oschina.net/question/2272552_2269641?sort=time
几个实现方式:
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);
}
场景二:
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);
}
场景三:
Resource[] resources;
try {
resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "/*.json");
for (int i = 0; i < resources.length; i++) {
try {
InputStream is = resources[i].getInputStream();
byte[] encoded = IOUtils.toByteArray(is);
String content = new String(encoded, Charset.forName("UTF-8"));
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}