import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.swing.*;
public class DosCmdW extends JFrame ...{
private static DosCmdW self;
ProcessBuilder pb = new ProcessBuilder("cmd.exe");
Process p ;
InputStream is;
OutputStream os;
byte[] buf = new byte[1024*16];
private JTextArea txaCmd = new JTextArea();
private JScrollPane sclpane = new JScrollPane(txaCmd,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
private JToolBar toolbar = new JToolBar();
private JButton btnExec = new JButton(new ImageIcon("../exec.jpg"));
private JButton btnClear = new JButton(new ImageIcon("../clear.jpg"));
private JPanel content = (JPanel)this.getContentPane();
Timer tm = new Timer(500,new ActionListener()...{
public void actionPerformed(ActionEvent arg0) ...{
if(is==null) return;
try...{
while(is.available()>0)...{
int count = is.read(buf,0,1024);
String str = new String(buf,0,count,"GB2312");
txaCmd.append(str);
}
}catch(Exception ex)...{
ex.printStackTrace();
}
}
});
private void init()...{
this.setTitle("cmd window");
this.setSize(500,200);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
btnExec.setBorderPainted(false);
btnClear.setBorderPainted(false);
Font font = new Font(null,Font.BOLD,14);
txaCmd.setFont(font);
txaCmd.setBackground(Color.BLACK);
txaCmd.setForeground(Color.WHITE);
toolbar.setSize(500,20);
sclpane.setSize(493,152);
content.setLayout(null);
content.add(toolbar);
content.add(sclpane);
toolbar.setFloatable(true);
toolbar.setRollover(false);
toolbar.add(btnExec);
toolbar.add(btnClear);
btnExec.setLocation(0, 0);
toolbar.setLocation(0,0);
sclpane.setLocation(0,toolbar.getHeight()+2);
try ...{
p = pb.start();
} catch (IOException e1) ...{
e1.printStackTrace();
}
is = p.getInputStream();
os = p.getOutputStream();
btnExec.addActionListener(new ActionListener()...{
public void actionPerformed(ActionEvent arg0) ...{
String strcmd = txaCmd.getSelectedText().trim();
if(strcmd.length()==0) return;
try ...{
os.write((strcmd+" ").getBytes());
os.flush();
} catch (Exception e) ...{
e.printStackTrace();
}
txaCmd.setCaretPosition(txaCmd.getDocument().getLength());
}
});
btnClear.addActionListener(new ActionListener()...{
public void actionPerformed(ActionEvent arg0) ...{
txaCmd.setText("");
}
});
tm.start();
}
private DosCmdW()...{
init();
}
public static DosCmdW getInstance()
...{
if(self!=null)
return self;
else...{
self = new DosCmdW();
return self;
}
}
}
以上代碼的要點在於,用ProcessBuilder創建cmd進程。然後獲取cmd進程的OutputStream和InputStream。往OutputStream中寫命令(例如“dir” “cd /”等等)的時候有兩個地方要著意:1.os.write((strcmd+"/r/n").getBytes()); 這句代碼中的“/r/n”不可以省略 2. os.flush(); 這句代碼一定要寫的 。
用定時器從InputStream 中讀取dos窗口的輸出,并將結果寫到JTextArea中。