温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-09-27 09:20:57 来源:亿速云 阅读:531 作者:小新 栏目:编程语言

这篇文章主要为大家展示了“基于Java如何实现文件和base64字符串转换”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“基于Java如何实现文件和base64字符串转换”这篇文章吧。

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

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

<dependency>      <groupId>commons-codec</groupId>      <artifactId>commons-codec</artifactId>      <version>1.13</version>    </dependency>

源码如下:

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");  }    /**   * 文件转化成base64字符串   * 将文件转化为字节数组字符串,并对其进行Base64编码处理   */  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);  }    /**   * base64字符串转化成文件,可以是JPEG、PNG、TXT和AVI等等   *   * @param base64FileStr   * @param filePath   * @return   * @throws Exception   */  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;  } }

以上是“基于Java如何实现文件和base64字符串转换”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI