importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.io.OutputStream;public classBase64Utils {/*** 文件读取缓冲区大小*/
private static final int CACHE_SIZE = 1024;/***
* BASE64字符串解码为二进制数据
*
*
*@parambase64
*@return*@throwsException*/
public static byte[] decode(String base64) throwsException {returnBase64.decode(base64.getBytes());
}/***
* 二进制数据编码为BASE64字符串
*
*
*@parambytes
*@return*@throwsException*/
public static String encode(byte[] bytes) throwsException {return newString(Base64.encode(bytes));
}/***
* 将文件编码为BASE64字符串
*
*
* 大文件慎用,可能会导致内存溢出
*
*
*@paramfilePath 文件绝对路径
*@return*@throwsException*/
public static String encodeFile(String filePath) throwsException {byte[] bytes =fileToByte(filePath);returnencode(bytes);
}/***
* BASE64字符串转回文件
*
*
*@paramfilePath 文件绝对路径
*@parambase64 编码字符串
*@throwsException*/
public static void decodeToFile(String filePath, String base64) throwsException {byte[] bytes =decode(base64);
byteArrayToFile(bytes, filePath);
}/***
* 文件转换为二进制数组
*
*
*@paramfilePath 文件路径
*@return*@throwsException*/
public static byte[] fileToByte(String filePath) throwsException {byte[] data = new byte[0];
File file= newFile(filePath);if(file.exists()) {
FileInputStream in= newFileInputStream(file);
ByteArrayOutputStream out= new ByteArrayOutputStream(2048);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = in.read(cache)) != -1) {
out.write(cache,0, nRead);
out.flush();
}
out.close();
in.close();
data=out.toByteArray();
}returndata;
}/***
* 二进制数据写文件
*
*
*@parambytes 二进制数据
*@paramfilePath 文件生成目录*/
public static void byteArrayToFile(byte[] bytes, String filePath) throwsException {
InputStream in= newByteArrayInputStream(bytes);
File destFile= newFile(filePath);if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out= newFileOutputStream(destFile);byte[] cache = new byte[CACHE_SIZE];int nRead = 0;while ((nRead = in.read(cache)) != -1) {
out.write(cache,0, nRead);
out.flush();
}
out.close();
in.close();
}/*** 使用Base64加密算法加密字符串
*
*@paramplainText*/
public staticString encodeStr(String plainText){byte[] b=plainText.getBytes();
org.apache.commons.codec.binary.Base64 base64= neworg.apache.commons.codec.binary.Base64();
b=base64.encode(b);
String s=newString(b);returns;
}/*** 使用Base64加密算法解密字符串
*
*@paramencodeStr*/
public staticString decodeStr(String encodeStr){byte[] b=encodeStr.getBytes();
org.apache.commons.codec.binary.Base64 base64= neworg.apache.commons.codec.binary.Base64();
b=base64.decode(b);
String s=newString(b);returns;
}
}