Process output only becomes available after the process has finished

前端 未结 5 1327
死守一世寂寞
死守一世寂寞 2021-01-07 03:50

I have a Runnable that reads Console output from an externally called exe (see below) and writes it to both a log file and a JTextArea.

But my Runnable doesn\'t show

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 04:03

    You could try the same logic with a SwingWorker instead. You can extend this class, instead of implementing runnable. It could take your Text area as a paramater, and you can publish the data, without having to deal with the SwingUtils.invokeLater, which is guiltily easier...

    Try:

    public class execute extends javax.swing.SwingWorker {  
          String line;
          Process p; 
          JTextArea jta;
    
          File f = new File( properties.prop.getProperty( "LOG_FILE_DIR" ) + "\\PartGen.log");
    
          public execute ( Process process , JTextArea jta ) {
              p = process;
              this.jta = jta;
          }
    
          //implements a method in the swingworker
          public void doInBackground() throws Exception {
            //Read Process Stream Output and write to LOG file
            BufferedReader is = new BufferedReader( new InputStreamReader(p.getInputStream()));
    
            while ( (line = is.readLine()) != null ) {
                osfile.writeline(line, f);
                publish(new String(line + "\n"));
            }   
            System.out.flush();  
            return null; 
      }
      //This will happen on the UI Thread.
      public void process(List lines){
          for(Object o : lines){
             jta.append((String)o);
          }
      }
    
      public void done(){
         try{
            get();
            //You will get here if everything was OK.  So show a popup or something to signal done.
         }catch(Exception ex){
             //this is where your IO Exception will surface, should you have one.
         }
      }
    }
    

    Also, in your calling code, which I assume is in your ui somewhere:

        Process p = new ProcessBuilder(command).start();
        execute ex = new execute( p , yourTextArea);
        ex.execute();
    

    I didnt attempt to compile this, so you may have to check against the API, but hopefully it will give you a gist of what to do.

提交回复
热议问题