在我的Java代码中,我调用了一个外部程序,我使用以下代码:
int returnCodeC = 0;
String cmnd = "dia -fa -fn res" + file1;
final Process processCC = Runtime.getRuntime().exec(cmnd);
BufferedReader bufC = new BufferedReader(new InputStreamReader(processCC.getInputStream()));
returnCodeC = processCC.waitFor();
} catch (Exception e1) {e1.printStackTrace();}}
调用外部程序dia的输出应写在名为file1的文件中 这一直到今天正常运作。我想问题是,当dia的输出很大时,我没有输出。 BufferReader是否有大小限制?
答案 0 :(得分:0)
这更像是一个评论,但是一个波普尔的答案,但我的不良声誉不允许我发表评论。
如果stdout或stderr溢出各自的缓冲区大小,您的进程将阻塞。
在shell中尝试命令,看看会发生什么,并启动线程来读取stdterr和stdout。
编辑:这是我在网上找到的内容,当我不需要stdout和stderr的内容时它适用于我,但只需要运行的命令。 我在processCC.waitFor()之前调用了dropOutput。
private int dropOutput(final Process p) {
final Thread t = new Thread("drop") {
@Override
public void run() {
_dropOutput(p);
};
};
t.start();
int ev = 0;
Timer timer = null;
try {
timer = new Timer(true);
final InterruptTimerTask interrupter = new InterruptTimerTask(Thread.currentThread());
timer.schedule(interrupter, 2 /*seconds*/* 1000 /*milliseconds per second*/);
if (p.waitFor() != 0) {
ev = p.exitValue();
}
} catch (final InterruptedException e) {
// e.printStackTrace();
} finally {
timer.cancel(); // If the process returns within the timeout period, we have to stop the interrupter
// so that it does not unexpectedly interrupt some other code later.
Thread.interrupted(); // We need to clear the interrupt flag on the current thread just in case
// interrupter executed after waitFor had already returned but before timer.cancel
// took effect.
//
// Oh, and there's also Sun bug 6420270 to worry about here.
}
return ev;
}
/**
* Just a simple TimerTask that interrupts the specified thread when run.
*/
class InterruptTimerTask extends TimerTask {
private final Thread thread;
public InterruptTimerTask(final Thread t) {
this.thread = t;
}
@Override
public void run() {
thread.interrupt();
}
}
private void _dropOutput(final Process p) {
final InputStream istrm = p.getInputStream();
// final InputStream istrm = p.getErrorStream();
final InputStreamReader istrmrdr = new InputStreamReader(istrm);
final BufferedReader buffrdr = new BufferedReader(istrmrdr);
@SuppressWarnings("unused")
String data;
try {
while ((data = buffrdr.readLine()) != null) {
// System.out.println(data);
}
} catch (final IOException e) {
// do nothing
}
}
答案 1 :(得分:0)
现在我认为我更好地理解了这个问题,我建议你使用processBuilder。它允许您对过程输出进行特殊控制。以下链接可能对您有所帮助:ProcessBuilder
proccess接收一个字符串数组作为参数,因此请使用String [] cmd = {"dia", "-fa", "-fn", "res"};