Base64编码实现二---使用org.apache.tomcat.util.codec.binary.Base64实现Base64

来源:互联网 发布:雨人医药软件 编辑:程序博客网 时间:2024/05/20 00:13

使用org.apache.tomcat.util.codec.binary.Base64实现Base64

package com.zero.io.base64;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import org.apache.tomcat.util.codec.binary.Base64;/** * 使用org.apache.tomcat.util.codec.binary.Base64实现Base64 * */public class BASE64EncoderTest2 {public static void main(String[] args) throws Exception {encode("src/pexels_photo.jpeg");//11Mbyte [] b = decode(encode("src/pexels_photo.jpeg"));createBase64File("D://apache_codec_base64.jpeg",b);}/** * 将文本转为字符串 * @param filePath 文件的路径 * @return String * @throws Exception */private static String encode(String filePath)  {BufferedInputStream inputStream = null;byte [] b = null;try {inputStream = new BufferedInputStream(new FileInputStream(filePath));b = new byte [inputStream.available()];inputStream.read(b);} catch (Exception e) {e.printStackTrace();} finally {if (null != inputStream){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}}return Base64.encodeBase64String(b);}/** * 将字符串转为byte[]数组 * @param fileString 文件使用encode方法转成的字符串数据 * @return byte [] * @throws Exception  */private static byte [] decode(String fileString) {return Base64.decodeBase64(fileString);}/** * 生成文件 * @param filepath 要生成的文件路径 * @param b * @return */public static boolean createBase64File(String filepath,byte [] b){BufferedOutputStream bufferedOutputStream = null;File file = null;try {file = new File(filepath);if (file.exists() && file.isFile()) {file.delete();}bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));bufferedOutputStream.write(b);bufferedOutputStream.flush();bufferedOutputStream.close();} catch (Exception e) {e.printStackTrace();return false;}return true;}}



原创粉丝点击