java实现返回cmd控制台所产生的信息
时间:2011-02-28 51cto博客 阿汐
以前写JAVA时想练练手写一个编辑器,涉及到JAVA代码的编译部分,考虑调用用javac.exe来编译,一下这段代码是用于将编译后产生的错误信息反馈到GUI上.同理,在cmd下执行的任何命令都可以反馈到GUI中.
//运行效果图
//以下代码用到了SWT相关的包
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.swtdesigner.SWTResourceManager;
public class CmdShell {
private Text text_1;
private Text text;
protected Shell shell;
/**
* Launch the application
* @param args
*/
public static void main(String[] args) {
try {
CmdShell window = new CmdShell();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window
*/
public void open() {
final Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
/**
* Create contents of the window
*/
protected void createContents() {
shell = new Shell(SWT.MIN | SWT.CLOSE | SWT.TITLE | SWT.RESIZE);
shell.setImage(SWTResourceManager.getImage(CmdShell.class, "/org/eclipse/jface/dialogs/images/title_banner.png"));
shell.setSize(415, 375);
shell.setText("CmdShellDemo");
final Button button = new Button(shell, SWT.NONE);
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
cmdShell();
}
});
button.setImage(SWTResourceManager.getImage(CmdShell.class, "/org/eclipse/jface/dialogs/images/message_info.gif"));
button.setText("执行命令");
button.setBounds(310, 25, 85, 24);
text = new Text(shell, SWT.BORDER);
text.setBackground(SWTResourceManager.getColor(202, 228, 240));
text.setBounds(10, 27, 294, 22);
text_1 = new Text(shell, SWT.V_SCROLL | SWT.BORDER | SWT.WRAP | SWT.H_SCROLL);
text_1.setForeground(SWTResourceManager.getColor(255, 0, 0));
text_1.setFont(SWTResourceManager.getFont("宋体", 10, SWT.NONE));
text_1.setBounds(10, 61, 385, 277);
final Label label = new Label(shell, SWT.NONE);
label.setText("请在下列输入框中输入CMD命令");
label.setBounds(10, 9, 294, 12);
//
}
//执行命令
private void cmdShell(){
int read;
try {
Process ps = Runtime.getRuntime().exec(text.getText());
InputStream is = ps.getInputStream();
InputStream ts=ps.getErrorStream();
StringBuffer out = new StringBuffer();
byte[] b = new byte[1024];
read=ts.read(b);
while ( (read = ts.read(b)) != -1) {
out.append(new String(b, 0, read));
}
text_1.append(new String(out));
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
|