import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;/**\* 使用sun.misc.BASE64Decoder和sun.misc.BASE64Encoder\* 完成文件转化二进制之间互相转化**/
public class BASE64test {/***\* @param path 目标文件\* @param path2 生成文件*/public static void encodeBase64File(String path,String path2) throws Exception {File file = new File(path);//创建目标文件对象FileInputStream inputFile = new FileInputStream(file);//输入流FileOutputStream out=new FileOutputStream(path2);//输出流OutputStreamWriter osw=new OutputStreamWriter(out);//文字写入流//文件读取时未使用缓冲,一次性读取byte[] buffer = new byte[(int) file.length()];inputFile.read(buffer);inputFile.close();//new BASE64Encoder().encode(buffer返回String类型的字符串//再使用文字输出流将其写出osw.write((new BASE64Encoder().encode(buffer)));osw.close();out.close();}public static void main(String[] args) {String path="C:\\Users\\Public\\Pictures\\Sample Pictures\\EAG42EqA_2560x1600.jpg";String path1="C:\\Users\\Public\\Pictures\\Sample Pictures\\EAG42EqA_2560x16002.txt";try {encodeBase64File(path,path1);File file=new File(path1);FileInputStream fis=new FileInputStream(file);FileOutputStream fos=new FileOutputStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\EAG42EqA_2560x16003.jpg");BASE64Decoder bd=new BASE64Decoder();byte[] b=bd.decodeBuffer(fis);fos.write(b);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}
}
}
java安装的目录下的jre/lib/rt.jar中有以下两个类实现base64的编码和解码:
sun.misc.BASE64Encodersun.misc.BASE64Decoder
下面是java实现:
public class Imagebase64 {static BASE64Encoder encoder = new sun.misc.BASE64Encoder();static BASE64Decoder decoder = new sun.misc.BASE64Decoder();public static void main(String[] args) {System.out.println(getImageBinary()); // image to base64base64StringToImage(getImageBinary()); // base64 to image}static String getImageBinary() {File f = new File("d://in.jpg");try {BufferedImage bi = ImageIO.read(f);ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(bi, "jpg", baos);byte[] bytes = baos.toByteArray();return encoder.encodeBuffer(bytes).trim();} catch (IOException e) {e.printStackTrace();}return null;}static void base64StringToImage(String base64String) {try {byte[] bytes1 = decoder.decodeBuffer(base64String);ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);BufferedImage bi1 = ImageIO.read(bais);File f1 = new File("d://out.jpg");ImageIO.write(bi1, "jpg", f1);} catch (IOException e) {e.printStackTrace();}}
}