果然多試幾個指令後,發現之前的用法,雖然沒什麼問題,但是遇到指令有帶 | 或是重新導向的語法時,問題就顯示出來,需改用下面的方式就解決了。

import java.io.*;
import java.net.*;
import java.util.*;

public class runshell {
    public static void main(String a[]) throws Exception {
        List cmds = new ArrayList();
        cmds.add("sh");
        cmds.add("-c");
        cmds.add("ps -ef | grep -v grep");
        ProcessBuilder pb =new ProcessBuilder(cmds);
        Process pl = pb.start();
        String line = "";
        BufferedReader p_in = new BufferedReader(new InputStreamReader(pl.getInputStream()));
        while ((line = p_in.readLine()) != null) {
            System.out.println(line);
        }
        p_in.close();
    }
}

mark528 發表在 痞客邦 PIXNET 留言(0) 人氣()