1 21 22 package org.armedbear.j.mail; 23 24 import java.io.InputStream ; 25 import java.io.IOException ; 26 import org.armedbear.j.FastStringBuffer; 27 28 public final class Base64Encoder 29 { 30 private static final int MAX_LINE_LENGTH = 72; 31 private static final int BUFFER_SIZE = (MAX_LINE_LENGTH * 3) / 4; 32 33 private InputStream inputStream; 34 35 public Base64Encoder(InputStream inputStream) 36 { 37 this.inputStream = inputStream; 38 } 39 40 public String encodeLine() throws IOException 41 { 42 byte[] buffer = new byte[BUFFER_SIZE]; 43 int length = inputStream.read(buffer, 0, buffer.length); 44 if (length <= 0) 45 return null; 46 if (length == buffer.length) 47 return encode(buffer); 48 byte[] newBuffer = new byte[length]; 50 System.arraycopy(buffer, 0, newBuffer, 0, length); 51 return encode(newBuffer); 52 } 53 54 private static String encode(byte[] input) 55 { 56 FastStringBuffer encoded = new FastStringBuffer(); 57 for (int i = 0; i < input.length; i += 3) 58 encoded.append(encodeThreeBytes(input, i)); 59 return encoded.toString(); 60 } 61 62 private static char[] encodeThreeBytes(byte[] input, int offset) 63 { 64 int[] in = new int[3]; 65 char[] out = new char[4]; 66 int n; 67 for (n = 0; n < 3; n++) { 68 if (offset >= input.length) 69 break; 70 if (input[offset] < 0) 73 in[n] = input[offset] + 256; 74 else 75 in[n] = input[offset]; 76 ++offset; 77 } 78 if (n > 0) { 79 out[0] = map[in[0] >> 2]; 80 out[1] = map[((in[0] & 3) << 4) | (in[1] >> 4)]; 81 out[2] = map[((in[1] & 0x0f) << 2) | (in[2] >> 6)]; 82 out[3] = map[in[2] & 0x3f]; 83 if (n < 3) { 86 out[3] = '='; 87 if (n < 2) 88 out[2] = '='; 89 } 90 } 91 return out; 92 } 93 94 public static final char[] getBase64Chars() 95 { 96 return map; 97 } 98 99 private static final char[] map = { 100 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 101 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 102 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 103 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 104 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 105 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 106 'w', 'x', 'y', 'z', '0', '1', '2', '3', 107 '4', '5', '6', '7', '8', '9', '+', '/' 108 }; 109 } 110 | Popular Tags |