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文件到指定的目录的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

运行JAR文件的先决条件在Linux系统上运行JAR文件需要安装Java运行时环境(JRE),它是执行Java应用程序所需的基本组件,包括Java虚拟机(JVM)、核心类库等。许多主流Linux发行版,如Ubuntu、Debian、Fedora、openSUSE等,都提供了JRE包的软件库,方便用户进行安装。后文将详细介绍在流行的发行版上安装JRE的步骤。设置完JRE后,可以根据个人喜好选择使用命令行终端或图形用户界面来启动JAR文件。您的选择可能取决于对Linuxshell的熟悉程度和个人偏好

Jasypt介绍Jasypt是一个java库,它允许开发员以最少的努力为他/她的项目添加基本的加密功能,并且不需要对加密工作原理有深入的了解用于单向和双向加密的高安全性、基于标准的加密技术。加密密码,文本,数字,二进制文件...适合集成到基于Spring的应用程序中,开放API,用于任何JCE提供程序...添加如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter2.1.1Jasypt好处保护我们的系统安全,即使代码泄露,也可以保证数据源的

使用场景1、下单成功,30分钟未支付。支付超时,自动取消订单2、订单签收,签收后7天未进行评价。订单超时未评价,系统默认好评3、下单成功,商家5分钟未接单,订单取消4、配送超时,推送短信提醒……对于延时比较长的场景、实时性不高的场景,我们可以采用任务调度的方式定时轮询处理。如:xxl-job今天我们采

一、Redis实现分布式锁原理为什么需要分布式锁在聊分布式锁之前,有必要先解释一下,为什么需要分布式锁。与分布式锁相对就的是单机锁,我们在写多线程程序时,避免同时操作一个共享变量产生数据问题,通常会使用一把锁来互斥以保证共享变量的正确性,其使用范围是在同一个进程中。如果换做是多个进程,需要同时操作一个共享资源,如何互斥呢?现在的业务应用通常是微服务架构,这也意味着一个应用会部署多个进程,多个进程如果需要修改MySQL中的同一行记录,为了避免操作乱序导致脏数据,此时就需要引入分布式锁了。想要实现分

springboot读取文件,打成jar包后访问不到最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

在Springboot+Mybatis-plus不使用SQL语句进行多表添加操作我所遇到的问题准备工作在测试环境下模拟思维分解一下:创建出一个带有参数的BrandDTO对象模拟对后台传递参数我所遇到的问题我们都知道,在我们使用Mybatis-plus中进行多表操作是极其困难的,如果你不使用Mybatis-plus-join这一类的工具,你只能去配置对应的Mapper.xml文件,配置又臭又长的ResultMap,然后再去写对应的sql语句,这种方法虽然看上去很麻烦,但具有很高的灵活性,可以让我们

1、自定义RedisTemplate1.1、RedisAPI默认序列化机制基于API的Redis缓存实现是使用RedisTemplate模板进行数据缓存操作的,这里打开RedisTemplate类,查看该类的源码信息publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//声明了key、value的各种序列化方式,初始值为空@NullableprivateRedisSe
