我不知道你,如果你想閱讀,但你知道,在Java世界中,你應該總是尋找實現自己之前的解決方案。常見問題的解決方案大多數時間來自Apache Commons或其他Apache項目。說除了你的解決方案以外的所有東西都不行,或者對你來說太複雜了,你只會花費你的時間和金錢(最終還是你的工作)。
Apache Commons Exec是你需要更快,更容易解決你的問題是什麼。
---- ----編輯
下面是如何捕捉子進程的輸出一些代碼。只是有它的一類,在PumpStreamHandler:
DefaultExecutor exec = new DefaultExecutor();
PumpStreamHandler streamHandler = new PumpStreamHandler();
exec.setStreamHandler(streamHandler);
CommandLine commandline = CommandLine.parse(command); //where command is your command line
exec.execute(commandline);
----編輯2 ----
這裏是你想使用OutputStream
捕捉消息的複製粘貼的解決方案:
public abstract class LogOutputStream extends OutputStream {
protected static final String LINE_SEPERATOR = System.getProperty("line.separator");
public static final int DEFAULT_BUFFER_LENGTH = 2048;
protected boolean hasBeenClosed = false;
protected byte[] buf;
protected int count;
private int bufLength;
public LogOutputStream() {
bufLength = DEFAULT_BUFFER_LENGTH;
buf = new byte[DEFAULT_BUFFER_LENGTH];
count = 0;
}
public void close() {
flush();
hasBeenClosed = true;
}
public void write(final int b) throws IOException {
if (hasBeenClosed) {
throw new IOException("The stream has been closed.");
}
if (b == 0) {
return;
}
if (count == bufLength) {
final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH;
final byte[] newBuf = new byte[newBufLength];
System.arraycopy(buf, 0, newBuf, 0, bufLength);
buf = newBuf;
bufLength = newBufLength;
}
buf[count] = (byte) b;
count++;
}
public void flush() {
if (count == 0) {
return;
}
if (count == LINE_SEPERATOR.length()) {
if (((char) buf[0]) == LINE_SEPERATOR.charAt(0)
&& ((count == 1) ||
((count == 2) && ((char) buf[1]) == LINE_SEPERATOR.charAt(1)))) {
reset();
return;
}
}
final byte[] theBytes = new byte[count];
System.arraycopy(buf, 0, theBytes, 0, count);
log(new String(theBytes));
reset();
}
private void reset() {
count = 0;
}
public abstract void log(String message);
}
然後,只需創建它的子類,使用更新UI的代碼實現public void log(String message)
,就完成了。
所以你要啓動一個外部程序,捕捉它是在應用程序中使用的輸出,並同時打印輸出到標準輸出? –
我要外只啓動Java虛擬機和Java編譯器,捕捉我的應用程序的輸出,我不介意,如果它在標準輸出打印,雖然我並不需要它! (如果我必須打印到兩者,那就這樣吧,這是我的煩惱中最少的) –
我很困惑什麼不適合你。你是否從'process.getInputStream()'讀取了啓動命令輸出的內容? –