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......");
                }
        }
}

 

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