import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* Base64工具类
*
*/
public class FileBase64Util {
public static String fileToBase64(File file) throws IOException {
String strBase64 = null;
try {
InputStream in = new FileInputStream(file);
// in.available()返回文件的字节长度
byte[] bytes = new byte[in.available()];
// 将文件中的内容读入到数组中
in.read(bytes);
strBase64 = encode(bytes); // 将字节流数组转换为字符串
in.close();
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return strBase64;
}
public static void base64ToFile(String strBase64, File toFile)
throws IOException {
String string = strBase64;
ByteArrayInputStream in = null;
FileOutputStream out = null;
try {
// 解码,然后将字节转换为文件
byte[] bytes = decode(string.trim());
// 将字符串转换为byte数组
in = new ByteArrayInputStream(bytes);
byte[] buffer = new byte[1024];
out = new FileOutputStream(toFile);
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread); // 文件写操作
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (out != null)
out.close();
if (in != null)
in.close();
}
}
/**
* 编码
*
* @param bstr
* @return String
*/
public static String encode(byte[] bstr) {
if (bstr == null)
return null;
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bstr);
}
/**
* 解码
*
* @param str
* @return string
* @throws IOException
*/
public static byte[] decode(String str) throws IOException {
if (str == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(str);
}
}