public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("mvn -version");
InputStream stderr = proc.getErrorStream();
InputStreamReader isrerr = new InputStreamReader(stderr);
BufferedReader brerr = new BufferedReader(isrerr);
InputStream stdin = proc.getInputStream();
InputStreamReader isrin = new InputStreamReader(stdin);
BufferedReader brin = new BufferedReader(isrin);
String line = null;
while ((line = brerr.readLine()) != null)
System.out.println(line);
while ((line = brin.readLine()) != null)
System.out.println(line);
int exitVal = proc.waitFor();
} catch (Throwable t) {
t.printStackTrace();
}
}
此代码不能正常工作,没有输出,并且进程无法停止。
帮帮我!谢谢提前。我想通过调用命令行在java程序中执行maven命令,但输出错误:输出错误java.io.IOException:无法运行程序“mvn”: 但如果我在命令行中运行相同的命令,它运行良好。答案 0 :(得分:0)
您应该使用proc.getInputStream()
除非您知道您的程序总是返回大量输出,否则最好在不同的线程中读取错误流和输入流。
然后使用proc.waitFor()
并从读者线程获取输出。
否则,您的进程可能会阻止,因为它无法提供输出。
示例代码: import java.io。*;
public class Test {
static class StreamReader extends Thread {
InputStream stream;
StreamReader(InputStream stream) {
this.stream = stream;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("mvn -version");
new StreamReader(proc.getInputStream()).start();
new StreamReader(proc.getErrorStream()).start();
int exitVal = proc.waitFor();
} catch (Throwable t) {
t.printStackTrace();
}
}
}