java 使用process build 使用sh 调用linux tar 压缩文件并加密
以下是使用 ProcessBuilder 在 Java 中使用 sh 调用 Linux tar 压缩文件并加密的示例代码:
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class TarEncrypt {
public static void main(String[] args) throws IOException {
// 设置要压缩的文件路径及文件名
String filePath = "/path/to/file/";
String fileName = "file.txt";
String fileFullPath = filePath + fileName;
// 设置压缩后的文件名和路径
String compressedName = fileName + ".tar.gz";
String compressedPath = filePath + compressedName;
// 设置加密密码
String password = "password123";
// 构建命令行参数
String[] cmd = {"sh", "-c", "tar czf - " + fileFullPath + " | openssl enc -e -aes256 -out " + compressedPath + " -k " + password};
// 创建 ProcessBuilder 对象并执行命令
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(filePath));
Process p = pb.start();
// 等待命令执行完成
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 输出命令执行结果
int exitValue = p.exitValue();
if (exitValue == 0) {
System.out.println("压缩成功");
} else {
System.out.println("压缩失败");
}
}
}
上述代码中,我们先设置要压缩的文件路径及文件名,以及压缩后的文件名和路径。然后,我们设置加密密码,并构建命令行参数。命令行参数中,我们首先使用 tar 命令将要压缩的文件压缩成 tar 格式,并将结果输出到标准输出流。然后,我们使用 openssl 命令将 tar 压缩包加密,并将结果输出到文件中。最后,我们创建 ProcessBuilder 对象并执行命令。在命令执行完成后,我们输出命令执行结果。如果命令执行成功,我们将输出“压缩成功”,否则将输出“压缩失败”
原文地址: https://www.cveoy.top/t/topic/eKoi 著作权归作者所有。请勿转载和采集!