JAVA文件转换为Base64

[[178773]]

 
 
  1. import java.io.File; 
  2. import java.io.FileInputStream; 
  3. import java.io.FileOutputStream; 
  4. import sun.misc.BASE64Decoder; 
  5. import sun.misc.BASE64Encoder; 
  6. public class FileToBase64 { 
  7.  /** 
  8.  * <p>将文件转成base64 字符串</p> 
  9.  * @param path 文件路径 
  10.  * @return 
  11.  * @throws Exception 
  12.  */ 
  13.  public static String encodeBase64File(String path) throws Exception { 
  14.  File file = new File(path); 
  15.  FileInputStream inputFile = new FileInputStream(file); 
  16.  byte[] buffer = new byte[(int)file.length()]; 
  17.  inputFile.read(buffer); 
  18.  inputFile.close(); 
  19.  return new BASE64Encoder().encode(buffer); 
  20.  } 
  21.  /** 
  22.  * <p>将base64字符解码保存文件</p> 
  23.  * @param base64Code 
  24.  * @param targetPath 
  25.  * @throws Exception 
  26.  */ 
  27.  public static void decoderBase64File(String base64Code,String targetPath) throws Exception { 
  28.  byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code); 
  29.  FileOutputStream out = new FileOutputStream(targetPath); 
  30.  out.write(buffer); 
  31.  out.close(); 
  32.  } 
  33.  /** 
  34.  * <p>将base64字符保存文本文件</p> 
  35.  * @param base64Code 
  36.  * @param targetPath 
  37.  * @throws Exception 
  38.  */ 
  39.  public static void toFile(String base64Code,String targetPath) throws Exception { 
  40.  byte[] buffer = base64Code.getBytes(); 
  41.  FileOutputStream out = new FileOutputStream(targetPath); 
  42.  out.write(buffer); 
  43.  out.close(); 
  44.  } 
  45.  public static void main(String[] args) { 
  46.  try { 
  47.  String base64Code =encodeBase64File("/Users/Crazy/Pictures/zyb2.jpg"); 
  48.  System.out.println(base64Code); 
  49.  decoderBase64File(base64Code, "/Users/Crazy/Desktop/zyb.png"); 
  50.  toFile(base64Code, "/Users/Crazy/Desktop/zyb.txt"); 
  51.  } catch (Exception e) { 
  52.  e.printStackTrace(); 
  53.  } 
  54.  } 

 【本文是专栏作者张勇波的原创文章,转载请通过获取作者授权】

THE END