2022
我们一起努力

怎么在Java将文件和base64字符串进行转换 - 编程语言

本文章向大家介绍怎么在Java将文件和base64字符串进行转换的基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Java的特点有哪些

Java的特点有哪些
1.Java语言作为静态面向对象编程语言的代表,实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程。
2.Java具有简单性、面向对象、分布式、安全性、平台独立与可移植性、动态性等特点。
3.使用Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。

需要引入的包:

<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字符串进行转换的全部内容了,希望大家多多支持云!

怎么在Java将文件和base64字符串进行转换 - 编程语言

赞(0)
文章名称:《怎么在Java将文件和base64字符串进行转换 - 编程语言》
文章链接:https://www.fzvps.com/83117.html
本站文章来源于互联网,如有侵权,请联系管理删除,本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。
图片版权归属各自创作者所有,图片水印出于防止被无耻之徒盗取劳动成果的目的。

评论 抢沙发

评论前必须登录!