栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于Java实现文件和base64字符串转换

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于Java实现文件和base64字符串转换

这篇文章主要介绍了基于Java实现文件和base64字符串转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

项目中遇到需要将图片转成base64编码的字符串的需求,但是,考虑到扩展性,写了一个可以转换任务类型文件的方法。需要引入的包:

    
      commons-codec
      commons-codec
      1.13
    

源码如下:

import sun.misc.base64Decoder;
import sun.misc.base64Encoder;
 
 
import java.io.*;
 
 
public class base64FileUtil {
 
 
  private static String targetFilePath = "E:\base2Img\target\test.txt";
 
 
  public static void main(String[] args) throws Exception {
    String fileStr = getFileStr("E:\base2Img\big test.txt");
    System.out.println("fileStr ===" + fileStr);
    System.out.println(generateFile(fileStr, targetFilePath));
    System.out.println("end");
  }
 
 
  
  public static String getFileStr(String filePath) {
    InputStream in = null;
    byte[] data = null;
    // 读取文件字节数组
    try {
      in = new FileInputStream(filePath);
      data = new byte[in.available()];
      in.read(data);
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
 in.close();
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    // 对字节数组base64编码
    base64Encoder encoder = new base64Encoder();
    // 返回 base64 编码过的字节数组字符串
    return encoder.encode(data);
  }
 
 
  
  public static boolean generateFile(String base64FileStr, String filePath) throws Exception {
    // 数据为空
    if (base64FileStr == null) {
      System.out.println(" 不行,oops! ");
      return false;
    }
    base64Decoder decoder = new base64Decoder();
 
 
    // base64解码,对字节数组字符串进行base64解码并生成文件
    byte[] byt = decoder.decodeBuffer(base64FileStr);
    for (int i = 0, len = byt.length; i < len; ++i) {
      // 调整异常数据
      if (byt[i] < 0) {
 byt[i] += 256;
      }
    }
    OutputStream out = null;
    InputStream input = new ByteArrayInputStream(byt);
    try {
      // 生成指定格式的文件
      out = new FileOutputStream(filePath);
      byte[] buff = new byte[1024];
      int len = 0;
      while ((len = input.read(buff)) != -1) {
 out.write(buff, 0, len);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      out.flush();
      out.close();
    }
    return true;
  }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135441.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号