java is not executing system command

孤街醉人 提交于 2020-01-11 11:12:23

问题


In the following program am giving name as "don" so the command will search activedirectory with all the names starting with don (like donald etc). But the line2 variable becomes null after the assignment from reader object and it never goes into the loop. What am i doing wrong? FYI: the command works when i give it on the command line.

try {
    Process p = Runtime.getRuntime().exec(
        "dsquery user -name " + name + "* -limit 200|dsget user -samid -display");
    p.waitFor();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line2 = reader.readLine();
    HashMap<String,String> hmap = new HashMap<String,String>();
    while (line2 != null) {
        line2 = line2.trim();
        if (line2.startsWith("dsget")||line2.startsWith("samid")) {
            continue;
        }
        String[] arr = line2.split(" ",1);
        hmap.put(arr[0].toLowerCase(),arr[1].toLowerCase());
        line2 = reader.readLine();
    }
    reader.close();
    line2 = reader.readLine();
}

回答1:


If I am not mistaken, the pipe (or redirection) requires to launch the programs with cmd.exe. Something like:

Process p = Runtime.getRuntime().exec("cmd /c dsquery user -name " + name + "* -limit 200|dsget user -samid -display");



回答2:


I can see at least some possible problems:

1) as PhiLho wrote: pipe and redirection is done by the shell (sh, bash,... or cmd.exe on Windows). You must handle it in the Java code or run your commands in a shell.

2) after calling waitFor() the Thread is blocked until the process terminates, the process only terminates if you "consume" it's InputStream. This is not happening since waitFor() is still waiting... Better to read and process the InputStream in an additional Thread (or call waitFor after reading the InputStream).

3) reading after closing (2 last lines) should throw an Exception.

Reading the ErrorStream could help find some errors, and checking the return of waitFor is also indicated.

EDIT:
actually there should be some Exceptions being throw by that code.
Are the Exceptions being reported (printStackTrace) or just ignored?



来源:https://stackoverflow.com/questions/3547166/java-is-not-executing-system-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!