Java调用shell命令涉及管道、重定向时不生效问题的解决方法

近日,因项目需求需要用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......");
                }
        }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章