我可以通过下面的代码在Eclipse中打印外部程序的输出(在网上找到,而不是我的)。我希望能够将命令传递给程序,然后打印程序的输出,但我不知道如何将命令传递给程序。任何建议将不胜感激,谢谢!
代码:
String line;
Process p = Runtime.getRuntime().exec("Z:/LPCXpresso/test10/Debug/arm-none-eabi-readelf.exe");
BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();
答案 0 :(得分:2)
首先,我建议使用ProcessBuilder代替Runtime.getRuntime().exec(...)
其次,为了能够与流程的不同流进行交互,您需要同时进行,即为每个流创建一个自己的Thread,您可以在其中与之交互。
这是一个示例代码,用于说明与Windows cmd.exe
中命令行提示的交互
public static void main(String... args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("cmd.exe");
Process proc = pb.start();
// handle each of proc's streams in a separate thread
ExecutorService handlerThreadPool = Executors.newFixedThreadPool(3);
handlerThreadPool.submit(new Runnable() {
@Override
public void run() {
// we want to write to the stdin of the process
BufferedWriter stdin = new BufferedWriter(
new OutputStreamWriter(proc.getOutputStream()));
// read from our own stdin so we can write it to proc's stdin
BufferedReader myStdin =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
do {
line = myStdin.readLine();
stdin.write(String.format("%s%n", line));
stdin.flush();
} while(! "exit".equalsIgnoreCase(line));
} catch(IOException e) {
e.printStackTrace();
}
}
});
handlerThreadPool.submit(new Runnable() {
@Override
public void run() {
// we want to read the stdout of the process
BufferedReader stdout = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line;
try {
while(null != (line = stdout.readLine())) {
System.out.printf("[stdout] %s%n", line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
});
handlerThreadPool.submit(new Runnable() {
@Override
public void run() {
// we want to read the stderr of the process
BufferedReader stderr = new BufferedReader(
new InputStreamReader(proc.getErrorStream()));
String line;
try {
while(null != (line = stderr.readLine())) {
System.err.printf("[stderr] %s%n", line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
});
// wait for the process to terminate
int exitCode = proc.waitFor();
System.out.printf("Process terminated with exit code %d%n", exitCode);
handlerThreadPool.shutdown();
}
在启动进程之前,您可以使用ProcessBuilder#redirectErrorStream(true)将进程stderr
简化并重定向到stdout
,然后只有2个线程,一个用于输入,另一个用于输出