packagejavaapplication1;importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.io.OutputStream;importorg.apache.commons.codec.binary.Base64;/****/
/***
* BASE64编码解码工具包
*
*
* 依赖javabase64-1.3.1.jar
*
*
*@authorIceWee
* @date 2012-5-19
*@version1.0*/
public classBase64Utils {/****/
/*** 文件读取缓冲区大小*/
private static final int CACHE_SIZE = 1024;public static final String _charset = "UTF-8";/****/
/***
* BASE64字符串解码为二进制数据
*
*
*@parambase64
*@return*@throwsException*/
public static byte[] decode(String str) throwsException {
Base64 _base64= newBase64();return_base64.decodeBase64(str.getBytes(_charset));
}/****/
/***
* 二进制数据编码为BASE64字符串
*
*
*@parambytes
*@return*@throwsException*/
public static String encode(byte[] bytes) throwsException {
Base64 _base64= newBase64();return newString(_base64.encodeBase64Chunked(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();
}
}