近日,因项目需求需要用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......");
}
}
}
本文探讨了在Java中调用包含管道操作的Shell命令时遇到的问题,并提供了解决方案。通过使用sh -c作为前缀,确保了Shell命令在Linux环境下正确执行,实现了预期的文件清理任务。
3772

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



