java实现linux文件的解压缩(确保md5sum一致)
package com.xlkh.device.utils; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths; public class LinuxTarGzUtil { private static final Logger logger = LoggerFactory.getLogger(LinuxTarGzUtil.class); /**
* 使用Linux命令压缩目录
* @param sourceDirPath 源目录路径(需为Linux路径格式)
* @param outputFilePath 输出文件路径
*/
public static String compress(String sourceDirPath, String outputFilePath) throws IOException {
Path sourcePath = Paths.get(sourceDirPath);
Path outputPath = buildOutputPath(sourcePath, outputFilePath); createParentDir(outputPath); // 构建新的压缩命令(保持MD5一致的关键实现)
String[] cmd = {
"/bin/bash",
"-c",
String.format(
"find %s -exec touch -h -t 197001010000.00 {} \\; && " +
"tar --sort=name --numeric-owner --no-same-permissions -cf - -C %s %s | " +
"gzip -n -f > %s", // 压缩并输出
sourcePath.toAbsolutePath(),
sourcePath.getParent().toAbsolutePath(),
sourcePath.getFileName(),
outputPath.toAbsolutePath()
)
}; return executeCommand(cmd, "压缩");
} /**
* 使用Linux命令解压文件
* @param inputFilePath 压缩文件路径
* @param outputDirPath 解压目录路径
*/
public static String decompress(String inputFilePath, String outputDirPath) throws IOException {
validateTarGzExtension(inputFilePath); // 创建输出目录
Files.createDirectories(Paths.get(outputDirPath)); // 构建解压命令
String[] cmd = {
"/bin/bash",
"-c",
String.format("tar -xzf %s --warning=no-timestamp --no-same-owner -C %s",
Paths.get(inputFilePath).toAbsolutePath(),
Paths.get(outputDirPath).toAbsolutePath())
}; return executeCommand(cmd, "解压");
} private static Path buildOutputPath(Path sourcePath, String outputPathStr) {
Path outputPath = Paths.get(outputPathStr).normalize(); if (Files.isDirectory(outputPath)) {
String sourceDirName = getLastNonEmptyPathPart(sourcePath);
return outputPath.resolve(sourceDirName + ".tar.gz");
}
return outputPath;
} private static void createParentDir(Path path) throws IOException {
Path parent = path.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
logger.info("已创建父目录:{}", parent);
}
} private static void validateTarGzExtension(String filename) {
if (!filename.toLowerCase().endsWith(".tar.gz")) {
throw new IllegalArgumentException("只支持.tar.gz格式文件");
}
} private static String executeCommand(String[] cmd, String operation) throws IOException {
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true); try {
Process process = pb.start();
StringBuilder output = new StringBuilder(); // 读取命令输出
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
} int exitCode = process.waitFor();
if (exitCode != 0) {
throw new IOException(operation + "失败,退出码:" + exitCode + "\n" + output);
} logger.info("{}成功:{}", operation, output);
return operation + "成功"; } catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(operation + "进程被中断", e);
}
} // 保留原有路径处理方法
private static String getLastNonEmptyPathPart(Path path) {
Path normalized = path.normalize();
int nameCount = normalized.getNameCount(); // 处理根目录特殊情况(如:/app)
if (nameCount == 0) {
String pathStr = normalized.toString();
int lastSeparator = pathStr.lastIndexOf(File.separatorChar);
return lastSeparator > 0 ? pathStr.substring(lastSeparator + 1) : pathStr;
} return normalized.getName(nameCount - 1).toString();
}
}
接口调用:

验证:


package com.xlkh.device.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class LinuxTarGzUtil {
private static final Logger logger = LoggerFactory.getLogger(LinuxTarGzUtil.class);
/**
* 使用Linux命令压缩目录
* @param sourceDirPath 源目录路径(需为Linux路径格式)
* @param outputFilePath 输出文件路径
*/
public static String compress(String sourceDirPath, String outputFilePath) throws IOException {
Path sourcePath = Paths.get(sourceDirPath);
Path outputPath = buildOutputPath(sourcePath, outputFilePath);
createParentDir(outputPath);
// 构建新的压缩命令(保持MD5一致的关键实现)
String[] cmd = {
"/bin/bash",
"-c",
String.format(
"find %s -exec touch -h -t 197001010000.00 {} \\; && " +
"tar --sort=name --numeric-owner --no-same-permissions -cf - -C %s %s | " +
"gzip -n -f > %s", // 压缩并输出
sourcePath.toAbsolutePath(),
sourcePath.getParent().toAbsolutePath(),
sourcePath.getFileName(),
outputPath.toAbsolutePath()
)
};
return executeCommand(cmd, "压缩");
}
/**
* 使用Linux命令解压文件
* @param inputFilePath 压缩文件路径
* @param outputDirPath 解压目录路径
*/
public static String decompress(String inputFilePath, String outputDirPath) throws IOException {
validateTarGzExtension(inputFilePath);
// 创建输出目录
Files.createDirectories(Paths.get(outputDirPath));
// 构建解压命令
String[] cmd = {
"/bin/bash",
"-c",
String.format("tar -xzf %s --warning=no-timestamp --no-same-owner -C %s",
Paths.get(inputFilePath).toAbsolutePath(),
Paths.get(outputDirPath).toAbsolutePath())
};
return executeCommand(cmd, "解压");
}
private static Path buildOutputPath(Path sourcePath, String outputPathStr) {
Path outputPath = Paths.get(outputPathStr).normalize();
if (Files.isDirectory(outputPath)) {
String sourceDirName = getLastNonEmptyPathPart(sourcePath);
return outputPath.resolve(sourceDirName + ".tar.gz");
}
return outputPath;
}
private static void createParentDir(Path path) throws IOException {
Path parent = path.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
logger.info("已创建父目录:{}", parent);
}
}
private static void validateTarGzExtension(String filename) {
if (!filename.toLowerCase().endsWith(".tar.gz")) {
throw new IllegalArgumentException("只支持.tar.gz格式文件");
}
}
private static String executeCommand(String[] cmd, String operation) throws IOException {
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
try {
Process process = pb.start();
StringBuilder output = new StringBuilder();
// 读取命令输出
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new IOException(operation + "失败,退出码:" + exitCode + "\n" + output);
}
logger.info("{}成功:{}", operation, output);
return operation + "成功";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(operation + "进程被中断", e);
}
}
// 保留原有路径处理方法
private static String getLastNonEmptyPathPart(Path path) {
Path normalized = path.normalize();
int nameCount = normalized.getNameCount();
// 处理根目录特殊情况(如:/app)
if (nameCount == 0) {
String pathStr = normalized.toString();
int lastSeparator = pathStr.lastIndexOf(File.separatorChar);
return lastSeparator > 0 ? pathStr.substring(lastSeparator + 1) : pathStr;
}
return normalized.getName(nameCount - 1).toString();
}
}
java实现linux文件的解压缩(确保md5sum一致)的更多相关文章
- Java实现压缩文件与解压缩文件
由于工作需要,需要将zip的压缩文件进行解压,经过调查发现,存在两个开源的工具包,一个是Apache的ant工具包,另一个就是Java api自带的工具包:但是Java自带的工具包存在问题:如果压缩或 ...
- java ZipOutputStream压缩文件,ZipInputStream解压缩
java中实现zip的压缩与解压缩.java自带的 能实现的功能比较有限. 本程序功能:实现简单的压缩和解压缩,压缩文件夹下的所有文件(文件过滤的话需要对File进一步细节处理). 对中文的支持需要使 ...
- java修改linux文件
package vedio.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Fil ...
- Linux的压缩/解压缩文件处理 zip & unzip
Linux的压缩/解压缩命令详解及实例 压缩服务器上当前目录的内容为xxx.zip文件 zip -r xxx.zip ./* 解压zip文件到当前目录 unzip filename.zip 另:有些服 ...
- Linux下zip格式文件的解压缩和压缩
Linux下zip格式文件的解压缩和压缩 Linux下的软件包很多都是压缩包,软件的安装就是解压缩对应的压缩包.所以,就需要熟练使用常用的压缩命令和解压缩命令.最常用的压缩格式有.tar.gz/tgz ...
- linux下java调用.so文件的方法1: JNI
摘自http://blog.163.com/squall_smile/blog/static/6034984020129296931793/ https://my.oschina.net/simabe ...
- Java在linux下调用C/C++生成的so文件
1.CplusUtil.java是java web工程中的一个工具类内容如下:CplusUtil.java package cn.undoner.utils; /** * Created by ${& ...
- Java实现对zip和rar文件的解压缩
通过java实现对zip和rar文件的解压缩
- Linux文件压缩、解压缩及归档工具一
主题Linux文件压缩.解压缩及归档工具 压缩工具很重要的,因为要经常到互联网下载包 一compress/uncompress compress [-dfvcVr] [-b maxbits] [fil ...
- 利用Java进行zip文件压缩与解压缩
摘自: https://www.cnblogs.com/alphajuns/p/12442315.html 工具类: package com.alphajuns.util; import java.i ...
随机推荐
- Bash Shell 30min 过家家
带你捅破窗户纸 - 备注 : @博客园 : 1. 为什么不支持 pdf 上传了呀 2. 网站分类不好用 3. 排版OA工具升级下, 例如 markdown 写出来好丑. 尝试升级下呢 ? 后记: 学如 ...
- HTTP/1.1、HTTP/2、HTTP/3
HTTP/1.1 相比 HTTP/1.0 性能上的改进: 使用长连接的方式改善了 HTTP/1.0 短连接造成的性能开销. 支持管道(pipeline)网络传输,只要第一个请求发出去了,不必等其回来, ...
- docker 版本号说明
17.03 版本以前 Docker CE 在 17.03 版本之前叫 Docker Engine, 版本说明参考这里 => Docker Engine release notes, 可以看到 D ...
- 【JDBC第5章】批量插入
第5章:批量插入 5.1 批量执行SQL语句 当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理.通常情况下比单独提交处理更有效率 JDBC的 ...
- python练习-爬虫(续)
流程: 1 设置url 2 设置消息头 3 设置消息体 4 获取响应 5 解析相应 6 验证数据 接下来就是查询数据了. # 识别图片中的文字 #image = Image.open('captcha ...
- pg获取tree完整的数据
一个表: DRGCode DRGParend DRGName 这样一个tree表结构. 任意查询string,希望得到一个查询完整的tree.怎么做? SELECT * FROM "DRG& ...
- Golang高性能引擎:ZKmall开源商城支撑百万级日活交易流畅运行
在电商业务高并发.低延迟的严苛场景下,技术栈的选择直接决定系统上限.ZKmall开源商城基于Golang技术生态,以协程级并发.毫秒级响应为核心优势,为百万级日活电商平台提供高性能解决方案.本文从架构 ...
- c数组与结构体
数组,存储同类型的复合类型:结构体,存储不同类型的复合类型,用于自定义数据结构. 计算机中,针对存储大量数据的集合,有着两种方式,一种是以块式集中存储数据,这就是数组的存储方式,大量同类型的数据集中放 ...
- springboot 集成Swagger2报错 Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is
springboot 集成Swagger2报错 Failed to start bean 'documentationPluginsBootstrapper'; nested exception is ...
- Jmeter接口关联总结
1.新建测试计划 输入相关接口如下: 本文以接口A(Phone Login)和接口B(Get ticket)两个接口为例进行关联 这两个接口的关系是:先执行接口A获取token作为参数,然后执行接口B ...