1 21 package gnu.mail.util; 22 23 import java.io.OutputStream ; 25 import java.io.FilterOutputStream ; 26 import java.io.IOException ; 27 28 36 public class QPOutputStream 37 extends FilterOutputStream 38 { 39 40 43 private static final char[] hex = {'0','1','2','3','4','5','6', 44 '7','8','9','A','B','C','D', 45 'E','F'}; 46 47 50 private int count; 51 52 55 private int bytesPerLine; 56 57 60 private boolean gotSpace; 61 62 65 private boolean gotCR; 66 67 68 72 77 public QPOutputStream(OutputStream stream, int length) 78 { 79 super(stream); 80 this.bytesPerLine = length; 81 this.count = 0; 82 this.gotSpace = false; 83 this.gotCR = false; 84 } 86 91 public QPOutputStream(OutputStream stream) 92 { 93 this(stream, 76); 94 } 96 97 101 105 public void flush() throws IOException 106 { 107 out.flush(); 108 } 110 117 public void write(byte[] bytes, int offset, int length) 118 throws IOException 119 { 120 121 int index; 123 124 for (index = offset; index < length; index++) 126 { 127 write(bytes[index]); 128 } 130 } 132 137 public void write(byte[] bytes) throws IOException 138 { 139 write(bytes, 0, bytes.length); 140 } 142 147 public void write(int b) throws IOException 148 { 149 b &= 0xff; 150 if (gotSpace) 151 { 152 if (b=='\n' || b=='\r') 153 output(' ', true); 154 else 155 output(' ', false); 156 gotSpace = false; 157 } 158 if (b==' ') 159 gotSpace = true; 160 else if (b=='\r') 161 { 162 gotCR = true; 163 outputCRLF(); 164 } 165 else if (b=='\n') 166 { 167 if (gotCR) 168 gotCR = false; 169 else 170 outputCRLF(); 171 } 172 if (b<' ' || b>=127 || b=='=') 173 output(b, true); 174 else 175 output(b, false); 176 } 178 182 public void close() throws IOException 183 { 184 out.close(); 185 } 187 193 protected void output(int b, boolean value) 194 throws IOException 195 { 196 if (value) 197 { 198 if ((count += 3) > bytesPerLine) 199 { 200 out.write('='); 201 out.write('\r'); 202 out.write('\n'); 203 count = 3; 204 } 205 out.write('='); 206 out.write(hex[b >> 4]); 207 out.write(hex[b & 0xf]); 208 } 209 else 210 { 211 if (++count > bytesPerLine) 212 { 213 out.write('='); 214 out.write('\r'); 215 out.write('\n'); 216 count = 1; 217 } 218 out.write(b); 219 } 220 } 222 226 private void outputCRLF() throws IOException 227 { 228 out.write('\r'); 229 out.write('\n'); 230 count = 0; 231 } 233 234 } | Popular Tags |