开发者

java is not executing system command

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();
}


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");


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜