这是做你想做的事情的一般代码。在这种情况下,既有输入也有输出:我someFile
将管道输入流程并将输出管道传输到System.out
. Files.copy()
并且ByteStreams.copy()
只是将一个InputStream
连接到一个OutputStream
. 然后我们等待命令完成。
final Process pr = Runtime.getRuntime().exec(cmd);
new Thread() {
public void run() {
try (OutputStream stdin = pr.getOutputStream()) {
Files.copy(someFile, stdin);
}
catch (IOException e) { e.printStackTrace(); }
}
}.start();
new Thread() {
public void run() {
try (InputStream stdout = pr.getInputStream()) {
ByteStreams.copy(stdout, System.out);
}
catch (IOException e) { e.printStackTrace(); }
}
}.start();
int exitVal = pr.waitFor();
if( exitVal == 0 )
System.out.println("Command succeeded!");
else
System.out.println("Exited with error code " + exitVal);
如果您在 Java 7 之前使用try-with-resources块运行,则使用更详细的版本:
final Process pr = Runtime.getRuntime().exec(cmd);
new Thread() {
public void run() {
OutputStream stdin = null;
try {
Files.copy(someFile, stdin = pr.getOutputStream());
}
catch (IOException e) { e.printStackTrace(); }
finally {
if( stdin != null ) {
try { stdin.close(); }
catch (IOException e) { e.printStackTrace(); }
}
}
}
}.start();
new Thread() {
public void run() {
InputStream stdout = null;
try {
ByteStreams.copy(stdout = pr.getInputStream(), System.out);
}
catch (IOException e) { e.printStackTrace(); }
finally {
if( stdout != null ) {
try { stdout.close(); }
catch (IOException e) { e.printStackTrace(); }
}
}
}
}.start();
int exitVal = pr.waitFor();
if( exitVal == 0 )
System.out.println("Command succeeded!");
else
System.out.println("Exited with error code " + exitVal);