java调用tar命令

16 篇文章 1 订阅
该博客展示了如何使用Java代码调用Linux命令`tar`和`openssl`来实现文件的7z压缩与解压。`zipWith7z`方法用于压缩,`unzipWith7z`方法用于解压,通过`processCmd`方法执行shell命令。在main方法中,对压缩和解压过程进行了演示。
摘要由CSDN通过智能技术生成

linux环境


import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.google.common.base.Strings;


public class ZipWithTools {

//tar -czvf - -C /root expect5.45 | openssl des3 -salt -k 123456 -out /root/expect.tar.gz
//srcPath /root
//srcFile expect5.45
//tarPath /root/expect.tar.gz
public static void zipWith7z(String srcPath, String srcFile, String tarPath, String password) throws Exception {
String cmdStr = "tar -czf - -C " + srcPath + " " + srcFile + " | openssl des3 -salt -k " + password + " -out " + tarPath;
processCmd(cmdStr);
}

// 解压
// openssl des3 -d -k 123456 -salt -in /root/expect.tar.gz | tar xzf - -C /home
//srcPath /root/expect.tar.gz
//tarPath /home
public static void unzipWith7z(String srcPath, String tarPath, String password) throws Exception {
String cmdStr = "openssl des3 -d -k " + password + " -salt -in " + srcPath + " | tar xzf - -C " + tarPath;
processCmd(cmdStr);
}

private static void processCmd(String cmdStr) {
List<String> command = new ArrayList<>();
command.add("/bin/sh");
command.add("-c");
command.add(cmdStr);
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
LineNumberReader ir = new LineNumberReader(
new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
String lines = new String(), line;
while ((line = ir.readLine()) != null) {
lines += line;
System.out.println(line);
}
if (!Strings.isNullOrEmpty(lines.trim()) && lines.contains("Error")) {
String msg = String.format("%s\n", lines);
throw new Exception("shu chu yi chang:\n" + msg);
}

if (process.isAlive()) {
process.waitFor();
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

//tar -czvf - -C /root expect5.45 | openssl des3 -salt -k 123456 -out /root/expect.tar.gz
String srcPath = "/root";
String srcFile = "expect5.45";
String tarPath = "/root/expect.tar.gz";
String password = "123456";
try {
ZipWithTools.zipWith7z(srcPath, srcFile, tarPath, password);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("zip finished");

srcPath = "/root/expect.tar.gz";
tarPath = "/home";
password = "123456";
try {
ZipWithTools.unzipWith7z(srcPath, tarPath, password);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("unzip finished");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值