1 20 21 package org.armedbear.j; 22 23 import java.io.BufferedReader ; 24 import java.io.IOException ; 25 import java.io.InputStream ; 26 import java.io.InputStreamReader ; 27 import java.io.UnsupportedEncodingException ; 28 29 public class ReaderThread extends Thread 30 { 31 private char[] buf = new char[4096]; 32 private InputStream inputStream; 33 private BufferedReader reader; 34 private boolean done = false; 35 private int timeOut = 10; 37 public ReaderThread(InputStream inputStream) 38 { 39 super("reader thread"); 40 this.inputStream = inputStream; 41 String encoding = 42 Editor.preferences().getStringProperty(Property.DEFAULT_ENCODING); 43 try { 44 reader = new BufferedReader (new InputStreamReader (inputStream, 45 encoding)); 46 } 47 catch (UnsupportedEncodingException e) { 48 Log.debug(e); 49 reader = new BufferedReader (new InputStreamReader (inputStream)); 50 } 51 } 52 53 public void setTimeOut(int n) 54 { 55 timeOut = n; 56 } 57 58 public void run() 59 { 60 while (!done) { 61 String s = read(); 62 if (s == null) 63 return; 64 update(filter(s)); 65 } 66 } 67 68 public void cancel() 69 { 70 interrupt(); 71 if (inputStream != null) { 72 try { 73 inputStream.close(); 74 } 75 catch (IOException e) { 76 Log.error(e); 77 } 78 inputStream = null; 79 } 80 } 81 82 private String read() 83 { 84 StringBuffer sb = new StringBuffer (); 85 try { 86 do { 87 int numChars = reader.read(buf, 0, buf.length); if (numChars < 0) { 89 done = true; 90 break; 91 } 92 if (numChars > 0) 93 sb.append(buf, 0, numChars); 94 Thread.sleep(timeOut); 95 } 96 while (reader.ready()); 97 } 98 catch (IOException e) { 99 return null; 100 } 101 catch (InterruptedException e) { 102 return null; 103 } 104 catch (Throwable t) { 105 return null; 106 } 107 return sb.toString(); 108 } 109 110 public String filter(String s) 111 { 112 return s; 113 } 114 115 public void update(String s) 116 { 117 } 118 } 119 | Popular Tags |