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.  } 

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

责任编辑:武晓燕 来源: 上下求索的Z先生博客
相关推荐

2023-11-07 08:35:26

2021-02-05 05:26:33

字节ASCII控制

2014-02-20 10:28:28

JavaScriptBase64

2021-08-26 05:27:08

Base64 字节流算法

2010-03-03 16:14:05

Python base

2021-03-05 09:10:19

base64编码

2021-09-07 08:59:09

编码Base64解码

2024-02-28 23:07:42

GolangBase64编码

2009-08-26 10:09:52

byte常用扩展

2022-06-06 08:31:05

Base64编码Base58

2019-07-23 08:55:46

Base64编码底层

2022-10-29 19:58:09

Base64Bashshell

2019-08-09 11:40:38

JavaScriptCSS技术

2024-03-14 10:31:33

JSbase64url

2023-03-01 11:02:12

2016-10-13 13:12:43

微信小程序javascript

2022-09-28 08:01:33

JavaScript二进制

2023-08-31 08:19:51

ViteSVGBase64

2009-10-14 09:27:30

VB.NET编码算法

2023-01-26 00:31:25

ASCIIBase64UTF-8
点赞
收藏

51CTO技术栈公众号