使用SwingWorker取得cmd数据
?
当doInBackground处理完后,会自动调用done方法。
我的例子是使用swingworker在后台取得adb logcat(该命令是安卓调试桥)命令产生的数据,你可以换成其他cmd命令,比如netstat命令
?
public class RunTest extends SwingWorker<Void, String>{
??? private JTextArea taConsole;
???
??? public RunTest(JTextArea taConsole){
??? ??? this.taConsole = taConsole;
??? }
??? @Override
??? protected Void doInBackground() throws Exception {
??? ???
??? ??? try {
??? ??? ??? String cmd ="adb logcat";
??? ??? ??? Process process = Runtime.getRuntime().exec(cmd);
??? ??? ??? InputStream input = process.getInputStream();
??? ??? ??? InputStreamReader inr = new InputStreamReader(input,"UTF-8");
??? ??? ??? BufferedReader reader = new BufferedReader(inr);???
??? ??? ??? String line = "";
??? ??? ??? while((line = reader.readLine()) != null){
??? ??? ??? ??? publish(line);//publish将产生的中间结果传递给process,由process方法进行处理
??? ??? ??? }
??? ??? ??? reader.close();
??? ??? ??? process.waitFor();
??? ??? }catch (Exception e) {
??? ??? ??? // TODO: handle exception
??? ??? }
??? ??? return null;
??? }
???
??? protected void done(){
??? ??? System.out.println("后台方法运行结束");
??? }
???
??? protected void process(List<String> list){
??? ??? for (String line :list){
??? ??? ??? if (line.trim().equals("")){
??? ??? ??? ??? continue;
??? ??? ??? }else {
??? ??? ??? ??? taConsole.append(line+"\n");
??????????????? //在这里可以将line分割,得到自己想要的形式,并显示在前台界面上
??????????????? //可以为日志分等级
??? ??? ??? ??? char ch = line.charAt(0);
??????????????? //...
??? ??? ??? }
??? ??? }
??? }
}