Guest User

InputStreamLineBuffer

a guest
Aug 29th, 2016
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.util.concurrent.ConcurrentLinkedQueue;
  4.  
  5. public class InputStreamLineBuffer{
  6.     private InputStream inputStream;
  7.     private ConcurrentLinkedQueue<String> lines;
  8.     private long lastTimeModified;
  9.     private Thread inputCatcher;
  10.     private boolean isAlive;
  11.  
  12.     public InputStreamLineBuffer(InputStream is){
  13.         inputStream = is;
  14.         lines = new ConcurrentLinkedQueue<String>();
  15.         lastTimeModified = System.currentTimeMillis();
  16.         isAlive = false;
  17.         inputCatcher = new Thread(new Runnable(){
  18.             @Override
  19.             public void run() {
  20.                 StringBuilder sb = new StringBuilder(100);
  21.                 int b;
  22.                 try{
  23.                     while ((b = inputStream.read()) != -1){  
  24.                         // read one char
  25.                         if((char)b == '\n'){
  26.                             // new Line -> add to queue
  27.                             lines.offer(sb.toString());
  28.                             sb.setLength(0); // reset StringBuilder
  29.                             lastTimeModified = System.currentTimeMillis();
  30.                         }
  31.                         else sb.append((char)b); // append char to stringbuilder
  32.                     }
  33.                 } catch (IOException e){
  34.                     e.printStackTrace();
  35.                 } finally {
  36.                     isAlive = false;
  37.                 }
  38.             }});
  39.     }
  40.     // is the input reader thread alive
  41.     public boolean isAlive(){
  42.         return isAlive;
  43.     }
  44.     // start the input reader thread
  45.     public void start(){
  46.         isAlive = true;
  47.         inputCatcher.start();
  48.     }
  49.     // has Queue some lines
  50.     public boolean hasNext(){
  51.         return lines.size() > 0;
  52.     }
  53.     // get next line from Queue
  54.     public String getNext(){
  55.         return lines.poll();
  56.     }
  57.     // how much time has elapsed since last line was read
  58.     public long timeElapsed(){
  59.         return (System.currentTimeMillis() - lastTimeModified);
  60.     }
  61. }
Add Comment
Please, Sign In to add comment