1. 程式人生 > >java 執行linux 本地命令

java 執行linux 本地命令

public static String executeCMD(final String[] cmdStrArr)
    {
        StringBuffer resBuf = new StringBuffer();
        Runtime rt = Runtime.getRuntime();
        BufferedReader bufr = null;

        try
        {
            Process p = rt.exec(cmdStrArr);

            int exitVal = p.waitFor();

            //執行指令碼失敗,重新發送
            if (0 != exitVal)
            {
                return executeCMDRepeat(cmdStrArr);
            }

            bufr = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = bufr.readLine()) != null)
            {
                resBuf.append(line).append("\r\n");
            }
        }
        catch (IOException e)
        {
        }
        catch (InterruptedException e)
        {
        }
        finally
        {
            if (bufr != null)
            {
                try
                {
                    bufr.close();
                }
                catch (Exception e)
                {
                }
            }
        }

        return resBuf.toString();
    }

    /**
     * 命令執行失敗重發
     * 
     * @param cmdStrArr
     * @return
     * @throws CacheException
     */
    public static String executeCMDRepeat(final String[] cmdStrArr)
    {
        StringBuffer resBuf = new StringBuffer();
        Runtime rt = Runtime.getRuntime();
        BufferedReader bufr = null;

        try
        {
            Process p = rt.exec(cmdStrArr);

            int exitVal = p.waitFor();

            bufr = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = bufr.readLine()) != null)
            {
                resBuf.append(line).append("\r\n");
            }
        }
        catch (IOException e)
        {
        }
        catch (InterruptedException e)
        {
        }
        finally
        {
            if (bufr != null)
            {
                try
                {
                    bufr.close();
                }
                catch (Exception e)
                {
                }

            }
        }

        return resBuf.toString();

    }