1 package com.quadcap.io; 2 3 40 41 import java.io.InputStream ; 42 import java.io.IOException ; 43 44 49 public class Base64InputStream extends InputStream { 50 InputStream in; 51 int accum = 0; 52 int cnt = -1; 53 boolean eof = false; 54 55 static int[] base64Map = new int[256]; 56 static { 57 byte[] b = Base64OutputStream.base64; 58 for (int i = 0; i < base64Map.length; i++) base64Map[i] = -1; 59 for (int i = 0; i < b.length; i++) { 60 base64Map[b[i]] = i; 61 } 62 base64Map['='] = 0; 63 } 64 65 public Base64InputStream(InputStream in) { 66 this.in = in; 67 } 68 69 final int readChar() throws IOException { 70 int c = eof ? -1 : in.read(); 71 while (c == '\r' || c == '\n') c = in.read(); 72 eof = c < 0; 73 return c; 74 } 75 76 public int read() throws IOException { 77 if (eof) return -1; 78 if (cnt < 0) { 79 int c1 = readChar(); 80 int c2 = readChar(); 81 int c3 = readChar(); 82 int c4 = readChar(); 83 if (eof) return -1; 86 87 int b1 = base64Map[c1]; 88 int b2 = base64Map[c2]; 89 int b3 = base64Map[c3]; 90 int b4 = base64Map[c4]; 91 92 if (b1 < 0 || b2 < 0 || b3 < 0 || b4 < 0) { 94 throw new IOException ("Bad base64 character"); 95 } 96 accum = (b1 << 18) | (b2 << 12) | (b3 << 6) | b4; 97 99 if (c3 == '=') { 100 cnt = 0; 101 accum >>= 16; 102 } else if (c4 == '=') { 103 cnt = 8; 104 accum >>= 8; 105 } else { 106 cnt = 16; 107 } 108 109 } 110 int ret = (accum >> cnt) & 0xff; 111 cnt -= 8; 112 return ret; 113 } 114 115 public void close() throws IOException { 116 in.close(); 117 } 118 } 119 | Popular Tags |