近日,因项目需求需要用java调用shell命令实现清理过时图片任务,发现代码生成出来的shell命令在linux系统后台直接执行,可以实现效果,但是,经过java代码运行,则达不到预期效果。经研究发现,因为该shell命令涉及了管道,这情况就有点不一样了,下面是针对Java调用shell命令涉及管道、重定向时不生效问题的解决方法,参考代码如下:
public class Test
{
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException
{
Process p;
String command = "find /opt/Img/ \"2019-11-22-*.jpg\" | xargs rm -rf"};
// 必须加上sh -c
p = Runtime.getRuntime().exec(new String[]{"sh","-c",command});
if(0==p.waitFor())
{
System.out.println("Command execute result is OK!");
}
else
{
System.out.println("Command execute result is fail......");
}
}
}