通过Java ProccesBuilder运行命令与在Shell中运行命令不同

时间:2010-04-05 08:28:37

标签: java command processbuilder

我正在试图弄清楚为什么我使用ProcessBuilder& amp;流程无效。我在Windows命令行运行“相同”命令,它按预期工作。它必须是他们不一样但我不能为我的生活找出原因。

命令是这样的:

ccm start -nogui -m -q -n ccm_admin -r developer -d /path/to/db/databasename -s http://hostname:8400 -pw Passw0rd789$

输出应该是一个单行字符串,我需要抓取并设置为环境变量(因此v。基本使用BufferedReader)。

我的Java代码,当它运行命令时会收到应用程序错误,如下所示,入口点为startCCMAndGetCCMAddress()

private static String ccmAddress = "";

private static final String DATABASE_PATH = "/path/to/db/databasename";
private static final String SYNERGY_URL = "http://hostname:8400";

private static final String USERNAME = "ccm_admin";
private static final String PASSWORD = "Passw0rd789$";
private static final String USER_ROLE = "developer";


public static List<String> getCCMStartCommand() {
    List<String> command = new ArrayList<String>();

    command.add("cmd.exe");
    command.add("/C");

    command.add("ccm");
    command.add("start");
    command.add("-nogui");
    command.add("-m");
    command.add("-q");
    command.add("-n "+USERNAME);
    command.add("-r "+USER_ROLE);
    command.add("-d "+DATABASE_PATH);
    command.add("-s "+SYNERGY_URL);
    command.add("-pw "+PASSWORD);

    return command;
}

private static String startCCMAndGetCCMAddress() throws IOException, CCMCommandException {
    int processExitValue = 0;

    List<String> command = getCCMStartCommand();

    System.err.println("Will run: "+command);

    ProcessBuilder procBuilder = new ProcessBuilder(command);
    procBuilder.redirectErrorStream(true);
    Process proc = procBuilder.start();
    BufferedReader outputBr = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    try {
        proc.waitFor();
    } catch (InterruptedException e) {
        processExitValue = proc.exitValue();
    }

    String outputLine = outputBr.readLine();
    outputBr.close();

    if (processExitValue != 0) {
        throw new CCMCommandException("Command failed with output: " + outputLine);
    }

    if (outputLine == null) {
        throw new CCMCommandException("Command returned zero but there was no output");
    }

    return outputLine;

}

System.err.println(...)的输出是:

Will run: [cmd.exe, /C, ccm, start, -nogui, -m, -q, -n ccm_admin, -r developer, -d /path/to/db/databasename, -s http://hostname:8400, -pw Passw0rd789$]

1 个答案:

答案 0 :(得分:1)

我认为你需要提供每个参数单独,并且没有前导/尾随空格,而不是连接选择的参数,例如“-pw PASSWORD”。这样你就可以使用正确的参数集调用进程(就像在命令行中看到的那样)