代码改变世界

工具函数

2010-06-28 11:15  小寇子  阅读(214)  评论(0)    收藏  举报
/**
     * 在控制台执行命令,并返回String字符串,默认操作系统为Windows
     */
    public static String executeCmd(String strCmd) throws Exception {
        String os = System.getProperty("os.name").toLowerCase();
        Process p = null;
        if (os.contains("linux")) {
            p = Runtime.getRuntime().exec("sh -c " + strCmd);
        } else {
            p = Runtime.getRuntime().exec("cmd -c " + strCmd);
        }
        StringBuilder sbCmd = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            sbCmd.append(line + "\n");
        }
        return sbCmd.toString();
    }