这个问题并不清楚,但我会假设 其他 Java 程序是一个命令行程序。
如果是这种情况,您将使用Runtime.exec()。
如果您想查看该程序的输出,这并不是那么简单。
以下是您如何将Runtime.exec() 与任何外部程序一起使用,而不仅仅是 Java 程序。
首先你需要一种非阻塞的方式来读取Standard.out和Standard.err
private class ProcessResultReader extends Thread
{
final InputStream is;
final String type;
final StringBuilder sb;
ProcessResultReader(@Nonnull final InputStream is, @Nonnull String type)
{
this.is = is;
this.type = type;
this.sb = new StringBuilder();
}
public void run()
{
try
{
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
this.sb.append(line).append("\n");
}
}
catch (final IOException ioe)
{
System.err.println(ioe.getMessage());
throw new RuntimeException(ioe);
}
}
@Override
public String toString()
{
return this.sb.toString();
}
}
然后你需要将这个类绑定到各自的InputStream和OutputStreamobjects。
try
{
final Process p = Runtime.getRuntime().exec(String.format("cmd /c %s", query));
final ProcessResultReader stderr = new ProcessResultReader(p.getErrorStream(), "STDERR");
final ProcessResultReader stdout = new ProcessResultReader(p.getInputStream(), "STDOUT");
stderr.start();
stdout.start();
final int exitValue = p.waitFor();
if (exitValue == 0)
{
System.out.print(stdout.toString());
}
else
{
System.err.print(stderr.toString());
}
}
catch (final IOException e)
{
throw new RuntimeException(e);
}
catch (final InterruptedException e)
{
throw new RuntimeException(e);
}
这几乎是我在需要 Runtime.exec() Java 中的任何内容时使用的样板。
更高级的方法是使用FutureTask 和Callable 或至少Runnable,而不是直接扩展Thread,这不是最佳做法。
注意:
@Nonnull 注释在 JSR305 库中。如果您正在使用 Maven,而您不是在使用 Maven,只需将此依赖项添加到您的 pom.xml。
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>1.3.9</version>
</dependency>