Java具有使用Runtime.exec對(duì)本地程序調(diào)用進(jìn)行重定向的能力,但是用重定向或者管道進(jìn)行命令調(diào)用將會(huì)出錯(cuò)。 異常代碼當(dāng)命令中含有管道(即命令符 | )的時(shí)候,就會(huì)出問(wèn)題,無(wú)法獲取相應(yīng)的信息: public static void getProcess() { String cmd = "ps aux|grep java"; Process pro; BufferedReader br = null; try { pro = Runtime.getRuntime().exec(cmd); br = new BufferedReader(new InputStreamReader(pro.getInputStream())); for (String buf = br.readLine(); buf != null; buf = br.readLine()) { System.out.println(buf); } } catch (Exception ex) { logger.error("getProcess exception : " + ex.getMessage()); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { logger.warn("bf close error" + ex.getMessage()); } } } } 解決方案解決方式很簡(jiǎn)單,用sh -c ,再加上原先的命令串即可解決問(wèn)題: public static void getProcess() { String cmd = "ps aux|grep java"; String[] commands = new String[]{"sh", "-c", cmd}; Process pro; BufferedReader br = null; try { pro = Runtime.getRuntime().exec(commands); br = new BufferedReader(new InputStreamReader(pro.getInputStream())); for (String buf = br.readLine(); buf != null; buf = br.readLine()) { System.out.println(buf); } } catch (Exception ex) { logger.error("getProcess exception : " + ex.getMessage()); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { logger.warn("bf close error" + ex.getMessage()); } } } } |
|