java执行Linux bash命令

来源:互联网 发布:acrobat xi mac 破解 编辑:程序博客网 时间:2024/05/18 09:28
//GetProcess.javaimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class GetProcess {public void executeCommand(String[] cmd){    Process proc = null;    try {        proc = Runtime.getRuntime().exec(cmd);        InputStream is = proc.getInputStream();        StreamGobbler localGob = new StreamGobbler(is);        new Thread(localGob).start();        Thread.sleep(1000);    } catch (IOException e) {        e.printStackTrace();    } catch (InterruptedException e) {        e.printStackTrace();    } finally{        if (proc != null){            proc.destroy();        }    }}public static void main(String[] args) {    GetProcess test = new GetProcess();    String cmd = "ps -ef| grep java | awk '{print $2}'";    test.executeCommand(new String[]{"sh", "-c", cmd});    }}class StreamGobbler implements Runnable {    InputStream is;    public StreamGobbler(InputStream is){        this.is = is;}public void run() {    BufferedReader br = new BufferedReader(new InputStreamReader(is));    String line= "";    try {        while ((line = br.readLine()) != null){            System.out.println(line);        }        br.close();    } catch (IOException e) {        e.printStackTrace();    }}}
原创粉丝点击