springboot怎么实现jar运行复制resources文件到指定的目录
来源:亿速云
时间:2024-04-21 08:54:35 233浏览 收藏
小伙伴们有没有觉得学习文章很有意思?有意思就对了!今天就给大家带来《springboot怎么实现jar运行复制resources文件到指定的目录》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!
springboot实现jar运行复制resources文件到指定的目录
1. 需求
在项目开发过程中需要将项目resources/static/目录下所有资源资源复制到指定目录。公司项目中需要下载视频文件,由于下载的有个html页面,对多路视频进行画面加载,用到对应的静态资源文件,如js,css.jwplayer,jquery.js等文件
maven打成的jar和平时发布的项目路径不通,所以在读取路径的时候获取的是jar的路径,无法获取jar里面的文件路径
2. 思路
根据我的需求,复制的思路大概是,先获取到resources/static/blog目录下文件清单,然后通过清单,循环将文件复制到指定位置(相对路径需要确保一致)
因为项目会被打成jar包,所以不能用传统的目录文件复制方式,这里需要用到Spring Resource:
Resource接口,简单说是整个Spring框架对资源的抽象访问接口。它继承于InputStreamSource接口。后续文章会详细的分析。
Resource接口的方法说明:
| 方法 | 说明 |
|---|---|
| exists() | 判断资源是否存在,true表示存在。 |
| isReadable() | 判断资源的内容是否可读。需要注意的是当其结果为true的时候,其内容未必真的可读,但如果返回false,则其内容必定不可读。 |
| isOpen() | 判断当前Resource代表的底层资源是否已经打开,如果返回true,则只能被读取一次然后关闭以避免资源泄露;该方法主要针对于InputStreamResource,实现类中只有它的返回结果为true,其他都为false。 |
| getURL() | 返回当前资源对应的URL。如果当前资源不能解析为一个URL则会抛出异常。如ByteArrayResource就不能解析为一个URL。 |
| getURI() | 返回当前资源对应的URI。如果当前资源不能解析为一个URI则会抛出异常。 |
| getFile() | 返回当前资源对应的File。 |
| contentLength() | 返回当前资源内容的长度 |
| lastModified() | 返回当前Resource代表的底层资源的最后修改时间。 |
| createRelative() | 根据资源的相对路径创建新资源。[默认不支持创建相对路径资源] |
| getFilename() | 获取资源的文件名。 |
| getDescription() | 返回当前资源底层资源的描述符,通常就是资源的全路径(实际文件名或实际URL地址)。 |
| getInputStream() | 获取当前资源代表的输入流。除了InputStreamResource实现类以外,其它Resource实现类每次调用getInputStream()方法都将返回一个全新的InputStream。 |
获取Resource清单,我需要通过ResourceLoader接口获取资源,在这里我选择了
org.springframework.core.io.support.PathMatchingResourcePatternResolver
3. 实现代码
/**
* 只复制下载文件中用到的js
*/
private void copyJwplayer() {
//判断指定目录下文件是否存在
ApplicationHome applicationHome = new ApplicationHome(getClass());
String rootpath = applicationHome.getSource().getParentFile().toString();
String realpath=rootpath+"/vod/jwplayer/"; //目标文件
String silderrealpath=rootpath+"/vod/jwplayer/silder/"; //目标文件
String historyrealpath=rootpath+"/vod/jwplayer/history/"; //目标文件
String jwplayerrealpath=rootpath+"/vod/jwplayer/jwplayer/"; //目标文件
String layoutrealpath=rootpath+"/vod/jwplayer/res/layout/"; //目标文件
/**
* 此处只能复制目录中的文件,不能多层目录复制(目录中的目录不能复制,如果循环复制目录中的目录则会提示cannot be resolved to URL because it does not exist)
*/
//不使用getFileFromClassPath()则报[static/jwplayerF:/workspace/VRSH265/target/classes/static/jwplayer/flvjs/] cannot be resolved to URL because it does not exist
//jwplayer
File fileFromClassPath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/"); //复制目录
FreeMarkerUtil.BatCopyFileFromJar(fileFromClassPath.toString(),realpath);
//silder
File flvjspath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/silder/"); //复制目录
FreeMarkerUtil.BatCopyFileFromJar(flvjspath.toString(),silderrealpath);
//history
File historypath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/history/"); //复制目录
FreeMarkerUtil.BatCopyFileFromJar(historypath.toString(),historyrealpath);
//jwplayer
File jwplayerpath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/jwplayer/"); //复制目录
FreeMarkerUtil.BatCopyFileFromJar(jwplayerpath.toString(),jwplayerrealpath);
//layout
File layoutpath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/res/layout/"); //复制目录
FreeMarkerUtil.BatCopyFileFromJar(layoutpath.toString(),layoutrealpath);
}4. 工具类FreeMarkerUtil
package com.aio.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.*;
/**
* @author:hahaha
* @creattime:2021-12-02 10:33
*/
public class FreeMarkerUtil {
/**
* 复制path目录下所有文件
* @param path 文件目录 不能以/开头
* @param newpath 新文件目录
*/
public static void BatCopyFileFromJar(String path,String newpath) {
if (!new File(newpath).exists()){
new File(newpath).mkdir();
}
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
//获取所有匹配的文件
Resource[] resources = resolver.getResources(path+"/*");
//打印有多少文件
for(int i=0;i<resources.length;i++) {
Resource resource=resources[i];
try {
//以jar运行时,resource.getFile().isFile() 无法获取文件类型,会报异常,抓取异常后直接生成新的文件即可;以非jar运行时,需要判断文件类型,避免如果是目录会复制错误,将目录写成文件。
if(resource.getFile().isFile()) {
makeFile(newpath+"/"+resource.getFilename());
InputStream stream = resource.getInputStream();
write2File(stream, newpath+"/"+resource.getFilename());
}
}catch (Exception e) {
makeFile(newpath+"/"+resource.getFilename());
InputStream stream = resource.getInputStream();
write2File(stream, newpath+"/"+resource.getFilename());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建文件
* @param path 全路径 指向文件
* @return
*/
public static boolean makeFile(String path) {
File file = new File(path);
if(file.exists()) {
return false;
}
if (path.endsWith(File.separator)) {
return false;
}
if(!file.getParentFile().exists()) {
if(!file.getParentFile().mkdirs()) {
return false;
}
}
try {
if (file.createNewFile()) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 输入流写入文件
*
* @param is
* 输入流
* @param filePath
* 文件保存目录路径
* @throws IOException
*/
public static void write2File(InputStream is, String filePath) throws IOException {
OutputStream os = new FileOutputStream(filePath);
int len = 8192;
byte[] buffer = new byte[len];
while ((len = is.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, len);
}
os.close();
is.close();
}
/**
*处理异常报错(springboot读取classpath里的文件,解决打jar包java.io.FileNotFoundException: class path resource cannot be opened)
**/
public static File getFileFromClassPath(String path){
File targetFile = new File(path);
if(!targetFile.exists()){
if(targetFile.getParent()!=null){
File parent=new File(targetFile.getParent());
if(!parent.exists()){
parent.mkdirs();
}
}
InputStream initialStream=null;
OutputStream outStream =null;
try {
Resource resource=new ClassPathResource(path);
//注意通过getInputStream,不能用getFile
initialStream=resource.getInputStream();
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
} catch (IOException e) {
} finally {
if (initialStream != null) {
try {
initialStream.close(); // 关闭流
} catch (IOException e) {
}
}
if (outStream != null) {
try {
outStream.close(); // 关闭流
} catch (IOException e) {
}
}
}
}
return targetFile;
}
}5.效果

理论要掌握,实操不能落!以上关于《springboot怎么实现jar运行复制resources文件到指定的目录》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
107 收藏
-
362 收藏
-
281 收藏
-
229 收藏
-
166 收藏
-
287 收藏
-
136 收藏
-
308 收藏
-
249 收藏
-
495 收藏
-
175 收藏
-
466 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习