Java操作Cmd命令

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 日期 : 2015年9月14日<br>
 * 項目 : Test<br>
 * 功能 : <br>
 */
public class Cmd {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            while (true) {
                //運行多級cmd可以用 && 讓命令在一行中運行
                List<String> list = run("cmd.exe /c d: && cd D:\\project && gulp phone");
                if (list == null || list.size() < 1) {
                    return;
                }
                String str = list.get(1);
                String[] arr = str.split("'");
                str = arr[1];
                if (arr.length != 2) {
                    return;
                }
                list = run("cmd.exe /c d: && cd D:\\project && npm install " + str);
                Thread.sleep(1000);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Description :
     * 
     * @return
     * @throws IOException
     */
    private static List<String> run(String cmd) throws IOException {
        BufferedReader br;
        //運行cmd
        Process p = Runtime.getRuntime().exec(cmd);
        //獲得輸出流
        br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        List<String> list = new ArrayList<String>();
        String line = null;
        //讀取內容
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            list.add(line);
        }
        //打印異常輸出流
        if (p.getErrorStream() != null) {
            br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String line2 = null;
            while ((line2 = br.readLine()) != null) {
                System.out.println(line2);
                list.add(line2);
            }
        }
        return list;
    }
}
發佈了23 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章