【问题标题】:Java and Runtime.getRuntime().exec(String cmd)Java 和 Runtime.getRuntime().exec(String cmd)
【发布时间】:2013-06-19 15:56:20
【问题描述】:

我正在尝试编写一个程序,它必须在 linux 终端中执行相同的代码:

openssl req -passout pass:abc -subj /C=US/ST=IL/L=Chicago/O=IBM          Corporation/OU=IBM Software Group/CN=John Smith/emailAddress=smith@abc.ibm.com -new > johnsmith.cert.csr

在终端中它工作正常,但在 Java 中却没有。 我尝试了类似的方法,但没有结果。

String[] cmd = { "openssl", "req -passout pass:abc -subj", "/C=US/ST=IL/L=Chicago/O=IBM          Corporation/OU=IBM Software Group/CN=John Smith/emailAddress=smith@abc.ibm.com", "-new > johnsmith.cert.csr" };
Runtime.getRuntime().exec(cmd);

你能解释一下,我想念什么。在此先感谢。 最好的祝愿安德烈

【问题讨论】:

  • 你试过了吗:Runtime.getRuntime().exec("openssl req -passout pass:abc -subj /C=US/ST=IL/L=Chicago/O=IBM Corporation/OU=IBM Software Group/CN=John Smith/emailAddress=smith@abc.ibm.com -new > johnsmith.cert.csr");
  • 您是否发现任何错误?如果是,错误信息是什么?
  • 阅读(并实施)所有 When Runtime.exec() won't 的建议。那可能会解决问题。如果不是,它应该提供更多关于失败原因的信息。然后忽略它引用exec 并使用ProcessBuilder 构建Process。还要将 String arg 拆分为 String[] args 以说明本身包含空格的参数。

标签: java linux terminal openssl


【解决方案1】:

您错过了流重定向> 是此处不存在的shell 功能这一事实。

您可以在命令前添加 /bin/sh -c 或使用 java 重定向输出:

Process proc = Runtime.getRuntime().exec(cmd);
InputStream in = proc.setOutputStream();
OutputStream out = new FileOutputStream("johnsmith.cert.csr");
int b;
while( (b = in.read()) != -1) {
   out.write(b);
}
out.flush();
out.close();

现在您可以从命令行中删除 "> johnsmith.cert.csr"。我个人更喜欢这个解决方案。

【讨论】:

  • 谢谢。我发现我的命令有 syntacsys 错误,但你是正确的文件。谢谢
猜你喜欢
  • 1970-01-01
  • 2012-10-14
  • 2011-07-15
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
相关资源
最近更新 更多