背景
项目开发过程中我们我们会遇到访问静态文件的情况,例如word书签模板,excel导入模板,条文法规文件等,在war包的情况下访问是没有问题的,如果使用jar包部署,使用相对路径访问会出现问题,本文就此问题给出解决方案。
配置
resources文件夹下创建静态目录systemfile,放入测试文件test.docx(文件名需要命名为英文)

image
pom文件resource/build节点设置打包编译忽略systemfile文件夹
true src/main/resources systemfile/* false src/main/resources systemfile/*
访问
使用ClassPathResource的getInputStream获取jar包中的文件的流暂存到磁盘的临时文件中,直接访问临时文件即可
String testFilePath = ClassPathFileUtil.getFilePath("systemfile/test.docx");
public static String getFilePath(String classFilePath) {
String filePath = "";
try {
String templateFilePath = "tempfiles/classpathfile/";
File tempDir = new File(templateFilePath);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
String[] filePathList = classFilePath.split("/");
String checkFilePath = "tempfiles/classpathfile";
for (String item : filePathList) {
checkFilePath += "/" + item;
}
File tempFile = new File(checkFilePath);
if (tempFile.exists()) {
filePath = checkFilePath;
} else {
//解析
ClassPathResource classPathResource = new ClassPathResource(classFilePath);
InputStream inputStream = classPathResource.getInputStream();
checkFilePath = "tempfiles/classpathfile";
for (int i = 0; i
注意
项目启动时,需要清除静态文件的临时文件,避免文件更新
@Component
@Order(value = 10)
public class StartUpContext implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String templateFilePath = "tempfiles/classpathfile/";
File tempDir = new File(templateFilePath);
FileSystemUtils.deleteRecursively(tempDir);
System.out.println("清除classpathfile临时文件成功");
}
【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】
© 版权声明
本平台(www.cooy.cn)的一切软件、教程及内容信息仅限用于学习和研究,付费仅为收集整理归类费用;
不得将上述内容用于商业或者非法用途,否则一切后果用户自行承担负责。本平台资源、内容、信息均来自来自用户上传,版权争议及其他问题与本平台无关。
您必须在下载后的24个小时之内从您的电脑或手机中彻底删除上述下载内容,如果您喜欢该程序或内容,请支持正版以获取更好的服务。我们非常重视版权问题,如有侵权请发送邮件至下方邮件(655465@qq.com),敬请谅解!
如发现违法违规内容,请联系下方邮箱举报,我们收到后将会第一时间处理。
THE END
暂无评论内容