1 19 20 package gnu.mail.util; 21 22 import java.io.*; 23 24 37 public class Base64OutputStream 38 extends FilterOutputStream 39 { 40 41 private byte buffer[]; 42 private int buflen; 43 private int count; 44 private int lineLength; 45 46 private static final char src[] = 47 { 48 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 49 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 50 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 51 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 52 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 53 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', 54 '8', '9', '+', '/' 55 }; 56 57 private static final int LF = 10, CR = 13, EQ = 61; 58 59 63 public Base64OutputStream(OutputStream out) 64 { 65 this(out, 76); 66 } 67 68 73 public Base64OutputStream(OutputStream out, int lineLength) 74 { 75 super(out); 76 buffer = new byte[3]; 77 this.lineLength = lineLength; 78 } 79 80 83 public void write(int c) 84 throws IOException 85 { 86 buffer[buflen++] = (byte)c; 87 if (buflen==3) { 88 encode(); 89 buflen = 0; 90 } 91 } 92 93 97 public void write(byte b[]) 98 throws IOException 99 { 100 write(b, 0, b.length); 101 } 102 103 107 public void write(byte b[], int off, int len) 108 throws IOException 109 { 110 for (int i=0; i<len; i++) 111 write(b[off+i]); 112 } 113 114 118 public void flush() 119 throws IOException 120 { 121 if (buflen>0) { 122 encode(); 123 buflen = 0; 124 } 125 out.flush(); 126 } 127 128 132 public void close() 133 throws IOException 134 { 135 flush(); 136 out.close(); 137 } 138 139 private void encode() 140 throws IOException 141 { 142 if ((count+4)>lineLength) 143 { 144 out.write(CR); 145 out.write(LF); 146 count = 0; 147 } 148 if (buflen==1) 149 { 150 byte b = buffer[0]; 151 int i = 0; 152 boolean flag = false; 153 out.write(src[b>>>2 & 0x3f]); 154 out.write(src[(b<<4 & 0x30) + (i>>>4 & 0xf)]); 155 out.write(EQ); 156 out.write(EQ); 157 } 158 else if (buflen==2) 159 { 160 byte b1 = buffer[0], b2 = buffer[1]; 161 int i = 0; 162 out.write(src[b1>>>2 & 0x3f]); 163 out.write(src[(b1<<4 & 0x30) + (b2>>>4 & 0xf)]); 164 out.write(src[(b2<<2 & 0x3c) + (i>>>6 & 0x3)]); 165 out.write(EQ); 166 } 167 else 168 { 169 byte b1 = buffer[0], b2 = buffer[1], b3 = buffer[2]; 170 out.write(src[b1>>>2 & 0x3f]); 171 out.write(src[(b1<<4 & 0x30) + (b2>>>4 & 0xf)]); 172 out.write(src[(b2<<2 & 0x3c) + (b3>>>6 & 0x3)]); 173 out.write(src[b3 & 0x3f]); 174 } 175 count += 4; 176 } 177 178 } 179 | Popular Tags |