java实现返回cmd掌握台所产生的信息[Java编程]
本文“java实现返回cmd掌握台所产生的信息[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
从前写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();
}
}
}
以上是“java实现返回cmd掌握台所产生的信息[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |