最近在使用java调用Runtime.getRuntime().exec方法执行linux命令压缩文件的时候,发现程序不报错,但是文件无法压缩,代码如下:
public static void zipFile(String filename, String path) {
File[] file = new File(path).listFiles();
File zipfile = new File(path + filename + ".zip");
if(zipfile.exists())
return;
if(file != null && file.length > 0){
try {
Process p = Runtime.getRuntime().exec("zip -m " + path + filename + ".zip " + path + "*" + filename + "*.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
System.out.println(sb.toString()); //打印命令行输出结果
p.waitFor();
p.destroy();
} catch (Exception e1) {
logger.error("IOException", e1);
}
}else
logger.info("无待压缩文件-------------------");
}
调试过程中通过下面代码
System.out.println(sb.toString()); //打印命令行输出结果
将linux命令的输出打印出来后发现命令报错如下
zip warning: name not matched: /root/data/20190723.txt
zip error: Nothing to do! (/root/data/20190723.zip)
解决方案
参考我的另一篇博客:
解决方法:https://blog.csdn.net/xinguopeng/article/details/97375191