最近在开发中,遇到了要在移动端查看图片或文件如(txt,ppt...)格式,那就开作,但是写完了之后发现了一些问题,就是保存的文件里都是base64格式的字符串,需要解码后才可以查看内容。 在浩瀚的网络中查找着。
/-------------------------------------------------------------------------------
* encodeBase64File:(将文件转成base64 字符串). <br/>
* @author guhaizhou@126.com
* @param path 文件路径
* @return
* @throws Exception
* @since JDK 1.6
*/
public static String encodeBase64File(String path) throws Exception {
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
return Base64.encodeToString(buffer,Base64.DEFAULT);
}
/--------------------------------------------------------------------Base64解码
/**
* decoderBase64File:(将base64字符解码保存文件). <br/>
* @author guhaizhou@126.com
* @param base64Code 编码后的字串
* @param savePath 文件保存路径
* @throws Exception
* @since JDK 1.6
*/
public static void decoderBase64File(String base64Code,String savePath) throws Exception {
//byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
byte[] buffer =Base64.decode(base64Code, Base64.DEFAULT);
FileOutputStream out = new FileOutputStream(savePath);
out.write(buffer);
out.close();
}