当前位置: 移动技术网 > IT编程>开发语言>Java > 基于Java实现文件和base64字符串转换

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

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了基于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;
  }
 
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网