Base64 工具类
2015-09-06 17:36
609 查看
</pre><pre name="code" class="java">package com.thunisoft.sffx.sy.gssjccapture.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @ClassName: Base64Util * @Description: BASE64工具类 * @author: chendj * @date: 2015-7-15 * */ public class Base64Util { /** * 日志 */ private static Log logger = LogFactory.getLog(Base64Util.class); /** * 将文件转成base64 字符串 * @param file 文件 * @return encodedFileString * @throws Exception */ public static String getFileByteString(File file) throws Exception { FileInputStream inputFile = new FileInputStream(file); // 取得文件大小 long length = file.length(); // 根据大小创建字节数组 byte[] buffer = new byte[(int) length]; inputFile.read(buffer); inputFile.close(); //base64转码 new String((new Base64()).encode(buffer)) String encodedFileString = Base64.encodeBase64String(buffer); return encodedFileString; } /** * 将base64字符解码保存文件 * @param base64Code 解码 * @param targetPath 要存的地址 * @return */ public static String decoderBase64File(String base64Code, String targetPath) { File file = new File(targetPath); try { if (file.exists()) { logger.error(targetPath + " 文件已经存在,不能转换为文件"); return null; } else { boolean createNewFile = file.createNewFile(); if (createNewFile) { logger.info("文件创建成功!"); } else { logger.info("文件创建遇到问题。"); } } byte[] buffer = new Base64().decode(base64Code); FileOutputStream out = new FileOutputStream(targetPath); out.write(buffer); out.close(); logger.info("文件保存成功!"); } catch (Exception e) { logger.error("文件base64编码转换失败!",e); targetPath = ""; } return targetPath; } /** * 将字符串转换成Base64编码 * @param tagertStr 要转换的字符串 * @return */ public static String convert(String tagertStr) { byte[] value; try { value = tagertStr.getBytes(Charsets.UTF_8); return new String(Base64.encodeBase64(value),Charsets.UTF_8); } catch (Exception e) { logger.error("字符串base64编码转换失败!" + e); } return null; } }
相关文章推荐
- 继承
- Egret的若干局限
- springMVC 实现ajax跨域请求
- JSONObject 包的依赖
- cookie小细节
- cookie细节
- Spring AOP实现原理
- 关于Fragment 使用重叠问题。
- MySQL时间转换/字符串截取/
- android开发之记录ListView滚动位置
- android开发之记录ListView滚动位置
- Regex正则表达式之“\d+”、RegexOptions.IgnoreCase、Groups(一)
- 表格进行多选编辑时,如何让一部分cell支持勾选,一部分不支持
- Android端OCR技术在身份证识别中的应用
- 模板的模板参数匹配报错问题
- POJ 3274 Gold Balanced Lineup hash
- Java 接口 实现和继承关系与区别
- android新组件RecyclerView使用介绍和进阶使用,替用Gallery
- git 删除index.lock文件
- 字符串深入学习