如果我正在执行类似" dir"的操作,我得到了一个正在运行并显示输出的代码。但如果我正在运行,则不显示输出" java -version"或来自java的其他命令。请帮忙:
public static void execJob(){
try{
ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
pb.directory(new File("src"));
Process process = pb.start();
IOThreadHandler outputHandler = new IOThreadHandler(process.getInputStream());
outputHandler.start();
process.waitFor();
System.out.println(outputHandler.getOutput());
}catch(Exception e) {
System.out.println(e.toString());
}
}
private static class IOThreadHandler extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
IOThreadHandler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
Scanner br = null;
try {
br = new Scanner(new InputStreamReader(inputStream));
String line = null;
while (br.hasNextLine()) {
line = br.nextLine();
output.append(line + System.getProperty("line.separator"));
}
} finally {
br.close();
}
}
答案 0 :(得分:2)
java -version
写入stderr,因此您需要pb.redirectErrorStream(true);
来捕获输出。
ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
pb.redirectErrorStream(true);
...
答案 1 :(得分:-1)
private static class IOThreadHandler extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
IOThreadHandler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
try (Scanner br = new Scanner(new InputStreamReader(inputStream))) {
String line = null;
while (br.hasNextLine()) {
line = br.nextLine();
output.append(line).append(System.getProperty("line.separator"));
}
}
}
public String getOutput() {
return output.toString();
}
}