我在我的 java 代码中调用了一个位于 jar 文件中某处的类(使用 java -classpath path/file.jar classname)。
这很有效,但前提是命令格式正确。如果我犯了一个错误getRuntime().exect(command)只是什么都不说。波纹管我有工作命令调用。当命令不起作用时,我想收到错误消息。如果我在 cmd (windows) 中犯了一个错误,我会得到一个正确的错误,我可以修复它。但不在我的 Java 应用程序中。
我留下了一个“if(input.ready())”,因为如果我不这样做,当命令行不正确时程序会冻结。执行“input.readLine()”时会发生这种情况。
// Execute a command with an argument that contains a space
String[] genKOSCommand = new String[] {
"java",
"-classpath",
Config.XDSI_TEST_KIT_HOME + "/xdsitest/lib/xdsitest.jar;"
+ Config.XDSI_TEST_KIT_HOME + "/xdsitest/classes",
"ca.etsmtl.ihe.xdsitest.docsource.SimplePublisher", "-k",
"C:/Softmedical/Viewer_Test/xdsi-testkit-2.0.4/xdsihome/usr/data/image14.dcm" };
Process child = Runtime.getRuntime().exec(genKOSCommand);
BufferedReader input = new BufferedReader(new InputStreamReader(
child.getInputStream()), 13107200);
String line = null;
if (input.ready()) {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
try {
child.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
关于如何从执行的命令中获取错误有什么建议吗?
谢谢
这是一段更完整的代码,用于打印command通过Process/Runtime运行某些代码时收到的错误:
final String command = "/bin/bash -c cat foo.txt | some.app";
Process p;
try {
p = Runtime.getRuntime().exec(command);
} catch (final IOException e) {
e.printStackTrace();
}
//Wait to get exit value
try {
p.waitFor();
final int exitValue = p.waitFor();
if (exitValue == 0)
System.out.println("Successfully executed the command: " + command);
else {
System.out.println("Failed to execute the following command: " + command + " due to the following error(s):");
try (final BufferedReader b = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
String line;
if ((line = b.readLine()) != null)
System.out.println(line);
} catch (final IOException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
通过使用 getErrorStream:
BufferedReader errinput = new BufferedReader(new InputStreamReader(
child.getErrorStream()));
Run Code Online (Sandbox Code Playgroud)
当处理来自不同流的输入时,最好在不同的线程中进行处理(因为这些调用(readLine等)是阻塞调用。
| 归档时间: |
|
| 查看次数: |
11853 次 |
| 最近记录: |