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");
}
}