Process p = Runtime.getRuntime().exec("myexe.exe");
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(p.getInputStream(), "GB2312"));
String value = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}finally{
IOUtils.close(br);
}
然后,输出如下,而不是我想要的字符串:
孩子:无法读取数据长度,错误代码109
答案 0 :(得分:2)
似乎问题出现了,因为exe的输出太长了。 ProcessBuilder可以解决它吗?
作为一般经验法则,您应该在致电Process
之前阅读waitFor
的输出(或使用背景Thread
在您waitFor
时阅读import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class PBDemo {
public static void main(String[] args) throws Exception {
String s;
ProcessBuilder pb = new ProcessBuilder("myexe.exe");
pb.redirectErrorStream(true);
try {
Process pro = pb.start();
InputConsumer ic = new InputConsumer(pro.getInputStream());
System.out.println("...Waiting");
int exitCode = pro.waitFor();
ic.join();
System.out.println("Process exited with " + exitCode);
} catch (Exception e) {
System.out.println("sorry" + e);
e.printStackTrace();
}
}
public static class InputConsumer extends Thread {
private InputStream is;
public InputConsumer(InputStream is) {
this.is = is;
start();
}
@Override
public void run() {
try {
int in = -1;
while ((in = is.read()) != -1) {
System.out.print((char) in);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}
)
InputConsumer
过去,我已经向submit
提供Observer Pattern,通过该del_id
可以通知新的输入或其他新的输入缓存输出,以便我可以在之后处理它该过程已根据您的需求完成