首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

施用SwingWorker取得cmd数据

2013-03-22 
使用SwingWorker取得cmd数据?SwingWorker可以在后台执行耗时的任务,而避免阻塞前端的用户程序,避免界面长

使用SwingWorker取得cmd数据

?

  • SwingWorker可以在后台执行耗时的任务,而避免阻塞前端的用户程序,避免界面长时间无响应
    SwingWorker有2个参数T?,?V??
  • T:为最终结果集 对应doInBackground方法前的返回值类型。通过调用swingworker的get方法可以取得返回值。??V:为中间结果集 对应process方法的参数list的数据类型
    在doInBackground方法中调用publish方法(注意publish方法只在SwingWorker类中实现)。可以发送中间结果V,然后这个结果由被发送到在EDT线程中的process方法中进行处理。

    当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);

    ??????????????? //...
    ??? ??? ??? }
    ??? ??? }
    ??? }
    }

  • 热点排行