使用java执行Linux 压缩为 .Z 文件命令
之前是想使用相应的API(compress)来做压缩,但是compress中只有解压的方法,并没有压缩的方法;此路不同,只能更换另外一种方法了——使用java执行Linux命令的方式。 .Z 包使用compress命令压缩(uncompress 解压);这个命令已经是相当老的unix命令。
String shellCmd = "compress -c "+文件路径;
//String shellCmd = "pwd";
//调用shell命名生成.Z文件
String s1 = ShellUtil.execShell(shellCmd);
logger.info("shell命令:"+shellCmd+"-->>>>>生成 .Z 文件返回结果:"+s1);
public class ShellUtil {
private static final Logger logger = LoggerFactory.getLogger(ShellUtil.class);
public static String execShell(String cmd) {
if(cmd==null || "".equals(cmd)){
logger.error("cmd为空");
return null;
}
try {
Process process = null;
BufferedReader reader = null;
// Linux下
String[] nowcmd = new String[]{"/bin/sh","-c", cmd};
// Windows下
//String[] nowcmd = new String[]{"cmd","/c",cmd});
process = Runtime.getRuntime().exec(nowcmd);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
//拼接
reader.close();
process.destroy();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
logger.error("执行execShell失败:"+cmd+">>>>>>>>>>>>>>>>>>"+e);
}
return null;
}
}

本文介绍了一种使用Java执行Linux命令来压缩文件为.Z格式的方法。由于Java自带的compress API缺少压缩功能,作者选择通过调用Linux的compress命令实现文件压缩。文中提供了一个ShellUtil工具类的具体实现。
7092

被折叠的 条评论
为什么被折叠?



