📄 decodeinputstream.txt
字号:
import java.io.InputStream;
import java.io.IOException;
public class DecodeInputStream extends InputStream
{
static private final byte PAD = (byte)'=';
static private byte[] REVERSE_ALPHABET = new byte[256];
static
{
for(int i = 0; i < 256; i++)
{
REVERSE_ALPHABET[i] = -1;
}
for(int i = 'A'; i <= 'Z'; i++)
{
REVERSE_ALPHABET[i] = (byte)(i - 'A');
}
for(int i = 'a'; i <= 'z'; i++)
{
REVERSE_ALPHABET[i] = (byte)(i - 'a' + 26);
}
for(int i = '0'; i <= '9'; i++)
{
REVERSE_ALPHABET[i] = (byte)(i - '0' + 52);
}
REVERSE_ALPHABET['+'] = 62;
REVERSE_ALPHABET['/'] = 63;
}
private InputStream in = null;
private int[] decodeArray = new int[4];
private int[] decodedArray = new int[3];
private int decodedArrayIndex = 0;
private int maxIndex = 0;
private boolean eofFound = false;
public DecodeInputStream(InputStream in)
{
this.in = in;
}
public int read() throws IOException
{
if(decodedArrayIndex >= maxIndex)
{
if(eofFound)
return -1;
int tmpIndex = 0;
int padCount = 0;
for(tmpIndex = 0; tmpIndex < 4;)
{
int b = in.read();
if(b < 0)
{
maxIndex = 0;
eofFound = true;
if(tmpIndex > 0)
throw new IOException("Invalid encoded stream.");
else
return -1;
}
b &= 0xFF;
if(b == PAD)
{
eofFound = true;
decodeArray[tmpIndex++] = 0;
padCount++;
}
else
{
int decoded = REVERSE_ALPHABET[b];
if(decoded < 0)
continue;
else
decodeArray[tmpIndex++] = decoded;
}
}
maxIndex = 3 - padCount;
if(maxIndex <= 0)
{
maxIndex = 0;
return -1;
}
decodedArrayIndex = 0;
decode();
decodeArray[0] = 0;
decodeArray[1] = 0;
decodeArray[2] = 0;
decodeArray[3] = 0;
}
return decodedArray[decodedArrayIndex++];
}
public void close() throws IOException
{
in.close();
}
private void decode()
{
int a = decodeArray[0] << 18 | decodeArray[1] << 12 | decodeArray[2] << 6 | decodeArray[3];
decodedArray[0] = (a >>> 16) & 0xFF;
decodedArray[1] = (a >>> 8) & 0xFF;
decodedArray[2] = a & 0xFF;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -