Groovy - threadedPrintStringBuffer


/ Published in: Groovy
Save to your folder(s)

None


Copy this code and paste it in your HTML
  1. def threadedPrintStringBuffer( StringBuffer aStringBuffer, Boolean aStop = false ) {
  2. // useful for real-time printing of process output
  3. /*
  4. Example use:
  5. def pb = new ProcessBuilder( 'cmd', '/c', 'dir' );
  6. def process = pb.start();
  7. def sb1 = new StringBuffer();
  8. process.consumeProcessOutput( sb1, sb1 );
  9. def stop = threadedPrintStringBuffer( sb1 );
  10. process.waitFor();
  11. stop = true;
  12. */
  13. int sbOldSize = 0;
  14. int sbNewSize = 0;
  15. def nap = { itNapTime = 100 -> Thread.sleep(itNapTime); } ;
  16. int sz, delta;
  17. def somethingToDo = {
  18. sz = aStringBuffer.length();
  19. delta = sz - sbOldSize;
  20. (delta > 0); // return
  21. } ;
  22. def doWork = {
  23. sbNewSize = sz;
  24. System.out.print( aStringBuffer.substring( sbOldSize, sbNewSize-1 ) );
  25. System.out.flush(); // very important !!!
  26. sbOldSize = sbNewSize;
  27. } ;
  28.  
  29. if ( somethingToDo() ) { doWork(); }
  30. nap();
  31. if ( aStop && !somethingToDo() ) { break; }
  32. } // end while
  33. } // end Thread
  34. return aStop; // !!!
  35. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.