// 将 s 进行 BASE64 编码
public static String getBASE64(String s) throws UnsupportedEncodingException {
if (s == null)
return null;
return new BASE64Encoder().encode(s.getBytes("UTF-8"));
}
// 将 字符串进行 BASE64 编码
public static String getBASE64ByCodec(String s) {
Base64 b64 = new Base64();
return b64.encodeToString(s.getBytes());
}
public static String getBASE64ByByte(byte[] by) {
Base64 b64 = new Base64();
return b64.encodeToString(by);
}
public static byte[] getFromBASE64(String s) {
if (s == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = null;
try {
b = decoder.decodeBuffer(s);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
// 创建从底层输入流中读取数据的缓冲输入流对象
bin = new BufferedInputStream(bais);
File file = new File("E://test.pdf");
// 创建到指定文件的输出流
fout = new FileOutputStream(file);
// 为文件输出流对接缓冲输出流对象
bout = new BufferedOutputStream(fout);
byte[] buffers = new byte[1024];
int len = bin.read(buffers);
while (len != -1) {
bout.write(buffers, 0, len);
len = bin.read(buffers);
}
// 刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
bout.flush();
public static byte[] base64ToByteArray(String s)
{
return base64ToByteArray(s, false);
}
public static byte[] altBase64ToByteArray(String s)
{
return base64ToByteArray(s, true);
}
private static byte[] base64ToByteArray(String s, boolean alternate) {
byte[] alphaToInt = alternate ? altBase64ToInt : base64ToInt;
int sLen = s.length();
int numGroups = sLen / 4;
if (4 * numGroups != sLen) {
throw new IllegalArgumentException("String length must be a multiple of four.");
}
int missingBytesInLastGroup = 0;
int numFullGroups = numGroups;
if (sLen != 0) {
if (s.charAt(sLen - 1) == '=') {
missingBytesInLastGroup++;
numFullGroups--;
}
if (s.charAt(sLen - 2) == '=') {
missingBytesInLastGroup++;
}
}
byte[] result = new byte[3 * numGroups - missingBytesInLastGroup];
int inCursor = 0; int outCursor = 0;
for (int i = 0; i < numFullGroups; i++) {
int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
result[(outCursor++)] = (byte)(ch0 << 2 | ch1 >> 4);
result[(outCursor++)] = (byte)(ch1 << 4 | ch2 >> 2);
result[(outCursor++)] = (byte)(ch2 << 6 | ch3);
}
if (missingBytesInLastGroup != 0) {
int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
result[(outCursor++)] = (byte)(ch0 << 2 | ch1 >> 4);
if (missingBytesInLastGroup == 1) {
int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
result[(outCursor++)] = (byte)(ch1 << 4 | ch2 >> 2);
}
}
return result;
}
private static int base64toInt(char c, byte[] alphaToInt)
{
int result = alphaToInt[c];
if (result < 0) {
throw new IllegalArgumentException("Illegal character " + c);
}
return result;
}