📄 base64encoder.java
字号:
package cn.jsprun.utils;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
public final class Base64Encoder extends FilterOutputStream {
private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '+', '/' };
private int charCount;
private int carryOver;
public Base64Encoder(OutputStream out) {
super(out);
}
public void write(int b) throws IOException {
if (b < 0) {
b += 256;
}
if (charCount % 3 == 0) {
int lookup = b >> 2;
carryOver = b & 3;
out.write(chars[lookup]);
}
else if (charCount % 3 == 1) {
int lookup = ((carryOver << 4) + (b >> 4)) & 63;
carryOver = b & 15;
out.write(chars[lookup]);
}
else if (charCount % 3 == 2) {
int lookup = ((carryOver << 2) + (b >> 6)) & 63;
out.write(chars[lookup]);
lookup = b & 63;
out.write(chars[lookup]);
carryOver = 0;
}
charCount++;
if (charCount % 57 == 0) {
out.write('\n');
}
}
public void write(byte[] b, int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
write(b[off + i]);
}
}
public void close() throws IOException {
if (charCount % 3 == 1) {
int lookup = (carryOver << 4) & 63;
out.write(chars[lookup]);
out.write('=');
out.write('=');
} else if (charCount % 3 == 2) {
int lookup = (carryOver << 2) & 63;
out.write(chars[lookup]);
out.write('=');
}
super.close();
}
public static String encode(String unencoded,String charsetName) {
ByteArrayOutputStream out = new ByteArrayOutputStream((int) (unencoded.length() * 1.37));
Base64Encoder encodedOut = new Base64Encoder(out);
byte[] bytes = null;
try {
bytes = unencoded.getBytes(charsetName);
} catch (UnsupportedEncodingException ignored) {
}
try {
encodedOut.write(bytes);
encodedOut.close();
return out.toString(charsetName);
} catch (IOException ignored) {
return null;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -