我正在努力弄清楚为什么我使用 ProcessBuilder & Process 通过 Java 执行的命令不起作用。我在 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$]