欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > springboot 框架把 resources下的zip压缩包, springboot 项目启动后解压到项目根目录工具类

springboot 框架把 resources下的zip压缩包, springboot 项目启动后解压到项目根目录工具类

2025/4/30 14:24:58 来源:https://blog.csdn.net/Drug_/article/details/147621195  浏览:    关键词:springboot 框架把 resources下的zip压缩包, springboot 项目启动后解压到项目根目录工具类

最近有一个需求,在开发的时候 有一些c++的扩展文件 需要放到服务器上,如果手动放上去,给用户部署项目就很麻烦,就根据这个需求,先把项目需要的 扩展文件 打包成zip压缩包 然后项目启动的时候 把resources文件夹下的 zip压缩包 解压到 项目根目录,这样就很方便。下面的工具类,在什么时机调用,大家可以根据自己的需求自行调整,我是在springboot启动的 run生命周期里 调用的
今天就分享一下 我封装的这个java版的 zip 解压工具类
直接上代码,有需要的小伙伴,复制直接可以使用:

package com.xx.xxx.utils;import org.springframework.core.io.ClassPathResource;import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.nio.file.Paths;/*** User:Json* Date: 2025/4/27**/
public class ZipUtils {public static boolean extractZipFromJar(String zipFileInJar, String destinationDirectory) {ClassPathResource resource = new ClassPathResource(zipFileInJar);Path targetDir = Paths.get(destinationDirectory); // 目标目录是根目录try (InputStream inputStream = resource.getInputStream();ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {// 创建目标目录,如果不存在if (!Files.exists(targetDir)) {Files.createDirectories(targetDir);}ZipEntry entry;while ((entry = zipInputStream.getNextEntry()) != null) {Path filePath = targetDir.resolve(entry.getName());// 如果是目录,则创建目录if (entry.isDirectory()) {Files.createDirectories(filePath);} else {if (Files.exists(filePath)) {System.out.println("文件已经存在,跳过解压: " + filePath);continue;}try (OutputStream outputStream = Files.newOutputStream(filePath)) {byte[] buffer = new byte[2048]; // 调整缓冲区大小以提高解压速度int length;while ((length = zipInputStream.read(buffer)) > 0) {outputStream.write(buffer, 0, length);}}}zipInputStream.closeEntry();}// 解压完成,输出日志System.out.println("ZIP 文件解压完成,已解压到:" + targetDir.toString());return true;} catch (IOException e) {// 记录详细的错误信息System.out.println("解压失败: " + e.getMessage());e.printStackTrace();return false;}}/*** 检查根目录是否存在某个文件夹* @param folderName 要检查的文件夹名称* @return 如果文件夹存在,返回 true;否则返回 false*/public static boolean isFolderExists(String folderName) {Path path = Paths.get(System.getProperty("user.dir"), folderName);  // 获取根目录下的文件夹路径return Files.exists(path) && Files.isDirectory(path);  // 检查文件夹是否存在且是目录}
}

下方是封面图:略过
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词