1 17 18 package org.apache.james.util; 19 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 23 29 public class CharTerminatedInputStream 30 extends InputStream { 31 32 35 private InputStream in; 36 37 40 private int match[]; 41 42 46 private int buffer[]; 47 48 52 private int pos = 0; 53 54 57 private boolean endFound = false; 58 59 68 public CharTerminatedInputStream(InputStream in, char[] terminator) { 69 if (terminator == null) { 70 throw new IllegalArgumentException ("The terminating character array cannot be null."); 71 } 72 if (terminator.length == 0) { 73 throw new IllegalArgumentException ("The terminating character array cannot be of zero length."); 74 } 75 match = new int[terminator.length]; 76 buffer = new int[terminator.length]; 77 for (int i = 0; i < terminator.length; i++) { 78 match[i] = (int)terminator[i]; 79 buffer[i] = (int)terminator[i]; 80 } 81 this.in = in; 82 } 83 84 91 public int read() throws IOException { 92 if (endFound) { 93 return -1; 95 } 96 if (pos == 0) { 97 int b = in.read(); 99 if (b == -1) { 100 throw new java.net.ProtocolException ("pre-mature end of data"); 102 } 103 if (b != match[0]) { 104 return b; 106 } 107 buffer[0] = b; 110 pos++; 111 } else { 112 if (buffer[0] != match[0]) { 113 return topChar(); 117 } 118 } 120 122 for (int i = 0; i < match.length; i++) { 125 if (i >= pos) { 126 int b = in.read(); 127 if (b == -1) { 128 return topChar(); 132 } 133 buffer[pos] = b; 135 pos++; 136 } 137 if (buffer[i] != match[i]) { 138 return topChar(); 140 } 141 } 142 endFound = true; 144 return -1; 145 } 146 147 152 private int topChar() { 153 int b = buffer[0]; 154 if (pos > 1) { 155 System.arraycopy(buffer, 1, buffer, 0, pos - 1); 157 } 158 pos--; 159 return b; 160 } 161 } 162 163 | Popular Tags |