背景
因为执行需要,需要把jar内templates文件夹下的的文件夹及文件加压到宿主机器的某个路径下, 以便执行对应的脚本文件
ps: 通过类加载器等方式,直接getfile遍历文件,在idea中运行是没问题的,但是当打包成jar运行就会出现问题,因为jar内文件的路径不是真实路径,会出现异常
java.io.filenotfoundexception: class path resource [xxx/xxx/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxx.jar!/boot-inf/classes!/xxx/xxx
方式一
知道文件名的情况下,无需一层一层的遍历,将文件路径都指定好,然后根据流文件拷贝
package com.aimsphm.practice; import lombok.extern.slf4j.slf4j; import com.google.common.collect.lists; import org.apache.commons.io.fileutils; import org.springframework.beans.factory.annotation.value; import org.springframework.boot.springapplication; import org.springframework.util.objectutils; import javax.annotation.postconstruct; import java.io.file; import java.io.ioexception; import java.io.inputstream; import java.net.url; import java.util.list; @component public class app { public static void main(string[] args) { springapplication.run(app.class, args); } @value("${customer.config.data-root:/usr/data/}") private string dataroot; @postconstruct public void initdatabase() { dataroot = dataroot.endswith("/") ? dataroot : dataroot + "/"; list<string> filelist = getfiles(); filelist.stream().filter(x -> !objectutils.isempty(x)).foreach(x -> { try { url resource = app.class.getclassloader().getresource(x); inputstream inputstream = resource.openstream(); if (objectutils.isempty(inputstream)) { return; } file file = new file(dataroot + x); if (!file.exists()) { fileutils.copyinputstreamtofile(inputstream, file); } } catch (ioexception e) { log.error("失败:",e) } }); } private list<string> getfiles() { return lists.newarraylist( "db/practice.db", "local-data/0/p-1.jpg", "local-data/0/p-2.jpg", "local-data/0/p-3.jpg", "local-data/0/p-4.jpg", "local-data/1/meter-1.png", "local-data/-1/yw-1.png", "local-data/sound/test.txt", "local-data/multi/1/meter-multi.jpg", "local-data/multi/-1/yewei.png", ""); } }
方式二
通过resource的方式,获取文件的描述信息,然后根据描述信息,获取文件的路径信息,然后通过拷贝流文件,将文件最终拷贝到指定的路径下
package com.example.demo.test; import lombok.extern.slf4j.slf4j; import org.springframework.core.io.resource; import org.springframework.core.io.support.pathmatchingresourcepatternresolver; import org.springframework.core.io.support.resourcepatternresolver; import org.springframework.stereotype.component; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; /** * 复制resource文件、文件夹 * * @author milla */ @component @slf4j public class jarfileutil { public void copyfolderfromjar() throws ioexception { this.copyfolderfromjar("templates", "/usr/data/files"); } /** * 复制path目录下所有文件到指定的文件系统中 * * @param path 文件目录 不能以/开头 * @param newpath 新文件目录 */ public void copyfolderfromjar(string path, string newpath) throws ioexception { path = preoperation(path, newpath); resourcepatternresolver resolver = new pathmatchingresourcepatternresolver(); //获取所有匹配的文件(包含根目录文件、子目录、子目录下的文件) resource[] resources = resolver.getresources("classpath:" + path + "/**"); //打印有多少文件 for (resource resource : resources) { //文件名 //以jar包运行时,不能使用resource.getfile()获取文件路径、判断是否为文件等,会报错: //java.io.filenotfoundexception: class path resource [xxx/xxx/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxx.jar!/boot-inf/classes!/xxx/xxx //文件路径 //file [/xxx/xxx] string description = resource.getdescription(); description = description.replace("\\", "/"); description = description.replace(path, "/"); //保留 /xxx/xxx description = description.replaceall("(.*\\[)|(]$)", "").trim(); //以“文件目录”进行分割,获取文件相对路径 //获取文件相对路径,/xxx/xxx //新文件路径 string newfilepath = newpath + "/" + description; if (newfilepath.endswith("/")) { file file = new file(newfilepath); //文件夹 if (file.exists()) { boolean mkdir = file.mkdir(); log.debug("路径[{}]创建是否成功状态:{} ", newfilepath, mkdir); } } else { //文件 inputstream stream = resource.getinputstream(); write2file(stream, newfilepath); } } } /** * 文件预处理 * * @param path 原文件路径 * @param newpath 目标路径 * @return 新的路径字符串 */ private static string preoperation(string path, string newpath) { if (!new file(newpath).exists()) { boolean mkdir = new file(newpath).mkdir(); log.debug("路径[{}]创建是否成功状态:{} ", newpath, mkdir); } if (path.contains("\\")) { path = path.replace("\\", "/"); } //保证没有重复的/出现 path = path.replaceall("(?<!\\g/|[^/])/+", ""); if (path.startswith("/")) { //以/开头,去掉/ path = path.substring(1); } if (path.endswith("/")) { //以/结尾,去掉/ path = path.substring(0, path.length() - 1); } return path; } /** * 输入流写入文件 * * @param is 输入流 * @param filepath 文件保存目录路径 * @throws ioexception ioexception */ public static void write2file(inputstream is, string filepath) throws ioexception { file destfile = new file(filepath); file parentfile = destfile.getparentfile(); boolean mkdirs = parentfile.mkdirs(); log.debug("路径[{}]创建是否成功状态:{} ", filepath, mkdirs); if (!destfile.exists()) { boolean newfile = destfile.createnewfile(); log.debug("路径[{}]创建是否成功状态:{} ", destfile.getpath(), newfile); } outputstream os = new fileoutputstream(destfile); 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(); } public static void main(string[] args) throws ioexception { //文件夹复制 string path = "templates"; string newpath = "d:/tmp"; new jarfileutil().copyfolderfromjar(path, newpath); } }
如果开发中使用一些文件操作依赖,可简化代码如下
<!--文件依赖 --> <dependency> <groupid>commons-fileupload</groupid> <artifactid>commons-fileupload</artifactid> <version>1.3.3</version> </dependency>
package com.example.demo.test; import lombok.extern.slf4j.slf4j; import org.apache.commons.io.fileutils; import org.springframework.core.io.resource; import org.springframework.core.io.support.pathmatchingresourcepatternresolver; import org.springframework.core.io.support.resourcepatternresolver; import org.springframework.stereotype.component; import javax.annotation.postconstruct; import java.io.file; /** * <p> * 功能描述: * </p> * * @author milla * @version 1.0 * @since 2024/05/31 16:30 */ @slf4j @component public class jarfileutil{ public static void main(string[] args) { jarfileutilinit = new jarfileutil(); init.copyfile2temp("//templates//shell//", "/usr/data/shell/files"); } @postconstruct public void copyfile2temp() { } public void copyfile2temp(string source, string target) { try { source = preoperation(source, target); resourcepatternresolver resolver = new pathmatchingresourcepatternresolver(); resource[] resources = resolver.getresources(source + "/**"); for (int i = 0; i < resources.length; i++) { resource resource = resources[i]; // resource.getfile() jar运行时候不能用该方法获取文件,因为jar的路径不对 string description = resource.getdescription(); description = description.replace("\\", "/"); description = description.replace(source, "/"); //保留 /xxx/xxx description = description.replaceall("(.*\\[)|(]$)", "").trim(); //以“文件目录”进行分割,获取文件相对路径 //获取文件相对路径,/xxx/xxx //新文件路径 string newfilepath = target + file.separator + description; file file = new file(newfilepath); if (newfilepath.endswith("/")) { boolean mkdirs = file.mkdirs(); log.debug("路径[{}]创建是否成功状态:{} ", newfilepath, mkdirs); } else { fileutils.copyinputstreamtofile(resource.getinputstream(), file); } } } catch (exception e) { log.error("文件拷贝异常:", e); } } private static string preoperation(string source, string target) { if (!new file(target).exists()) { boolean mkdir = new file(target).mkdir(); log.debug("路径[{}]创建是否成功状态:{} ", target, mkdir); } if (source.contains("\\")) { source = source.replace("\\", "/"); } //保证没有重复的/出现 source = source.replaceall("(?<!\\g/|[^/])/+", ""); if (source.startswith("/")) { //以/开头,去掉/ source = source.substring(1); } if (source.endswith("/")) { //以/结尾,去掉/ source = source.substring(0, source.length() - 1); } return source; } }
通过这种方式,就能将正在运行的jar中的文件,拷贝到指定的路径下,记录备查
到此这篇关于springboot jar运行时如何将jar内的文件拷贝到文件系统中的文章就介绍到这了,更多相关springboot jar运行文件拷贝内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论