如何在java中的jtextarea上显示shell命令输出?
答
你可以得到下面的代码片段shell命令的输出,在while循环设置的JTextArea。
try {
String cmd = "java"; // Set shell command
Process child = Runtime.getRuntime().exec(cmd);
InputStream lsOut = child.getInputStream();
InputStreamReader r = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(r);
// read the child process' output
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
// You should set JtextArea
}
} catch (Exception e) { // exception thrown
System.err.println("Command failed!");
}
+0
我认为你的代码示例需要改变来处理Swing线程问题。 – 2011-04-17 13:48:33
答
您需要读取标准输出作为进程输入流并使用另一个线程的事件队列更新JTextArea。请参见下面的示例代码:
public class OutputDisplayer implements Runnable {
protected final JTextArea textArea_;
protected Reader reader_ = null;
public OutputDisplayer(JTextArea textArea) {
textArea_ = textArea;
}
public void commence(Process proc) {
InputStream in = proc.getInputStream();
reader_ = new InputStreamReader(in);
Thread thread = new Thread(this);
thread.start();
}
public void run() {
StringBuilder buf = new StringBuilder();
try {
while(reader_ != null) {
int c = reader_.read();
if(c==-1) return;
buf.append((char) c);
setText(buf.toString());
}
} catch (IOException ioe) {
buf.append("\n\nERROR:\n"+ioe.toString());
setText(buf.toString());
} finally {
try {
reader_.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private void setText(final String text) {
EventQueue.invokeLater(new Runnable() {
public void run() {
textArea_.setText(text);
}
});
}
}
+0
调用.setText()似乎消耗大量内存。请看这个,因为我正在请求帮助。谢谢。 http://stackoverflow.com/questions/11302982/jtextarea-consumes-a-lot-of-memory – jobobo 2012-07-03 07:52:31
答
除了在我的评论我的两个环节上面,我创建并使用了TextAreaOutputStream,有助于输出流数据重定向到一个textarea:
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class TextAreaOutputStream extends OutputStream {
private final JTextArea textArea;
private final StringBuilder sb = new StringBuilder();
private String title;
public TextAreaOutputStream(final JTextArea textArea, String title) {
this.textArea = textArea;
this.title = title;
sb.append(title + "> ");
}
@Override
public void flush() {
}
@Override
public void close() {
}
@Override
public void write(int b) throws IOException {
if (b == '\r')
return;
if (b == '\n') {
final String text = sb.toString() + "\n";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
sb.setLength(0);
sb.append(title + "> ");
}
sb.append((char) b);
}
}
请有看看回答你的问题的两个不错的链接:[Redirect-output-stderr-stdout-JTextArea](http://www.coderanch.com/t/458147/GUI/java/Redirect-output-stderr-stdout-JTextArea)和这个经典:[当Runtime.exec()不会](http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html)。希望这可以帮助! – 2011-04-17 13:43:48