一、前言
基于apache的commons-codec包的org.apache.commons.codec.binary.Base64算法,将图片转换文字代码示例,详情参见示例说明。
二、示例说明
import java.io.File; @b@import java.io.FileInputStream; @b@import java.io.FileOutputStream; @b@@b@import org.apache.commons.codec.binary.Base64;@b@ @b@ @b@public class File2Code { @b@ @b@ /** @b@ * <p>将文件转成base64 字符串</p> @b@ * @param path 文件路径 @b@ * @return @b@ * @throws Exception @b@ */ @b@ public static byte[] encodeBase64File(String path) throws Exception { @b@ File file = new File(path); @b@ FileInputStream inputFile = new FileInputStream(file); @b@ byte[] buffer = new byte[(int)file.length()]; @b@ inputFile.read(buffer); @b@ inputFile.close(); @b@ return new Base64().encode(buffer); @b@ } @b@ /** @b@ * <p>将base64字符解码保存文件</p> @b@ * @param base64Code @b@ * @param targetPath @b@ * @throws Exception @b@ */ @b@ public static void decoderBase64File(String base64Code,String targetPath) throws Exception { @b@ byte[] buffer = new Base64().decodeBase64(base64Code); @b@ FileOutputStream out = new FileOutputStream(targetPath); @b@ out.write(buffer); @b@ out.close(); @b@ } @b@ /** @b@ * <p>将base64字符保存文本文件</p> @b@ * @param base64Code @b@ * @param targetPath @b@ * @throws Exception @b@ */ @b@ public static void toFile(String base64Code,String targetPath) throws Exception { @b@ byte[] buffer = base64Code.getBytes(); @b@ FileOutputStream out = new FileOutputStream(targetPath); @b@ out.write(buffer); @b@ out.close(); @b@ } @b@ public static void main(String[] args) { @b@ try { @b@ /**@b@ String base64Code =new String(encodeBase64File("D:\\test1.txt")); @b@ System.out.println(base64Code); @b@ decoderBase64File(base64Code, "D:\\2.txt"); @b@ toFile(base64Code, "D:\\3.txt"); @b@ **/ @b@ String base64Code =new String(encodeBase64File("D:\\test1.zip")); @b@ System.out.println(base64Code); @b@ decoderBase64File(base64Code, "D:\\2.zip"); @b@ toFile(base64Code, "D:\\3.txt"); @b@ @b@ } catch (Exception e) { @b@ e.printStackTrace(); @b@ } @b@ } @b@ @b@}