当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现文件和base64流的相互转换功能示例

Java实现文件和base64流的相互转换功能示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例讲述了java实现文件和base64流的相互转换功能。分享给大家供大家参考,具体如下:

import java.io.fileinputstream;
import java.io.fileoutputstream;
import sun.misc.base64decoder;
import sun.misc.base64encoder;
/**
 * 文件与base64的互相转换操作
 */
public class testfile {
public static void main(string[] args) {
testfile t = new testfile();
try {
string ret = t.encodebase64file("d://ie和火狐js或css差异.docx");
system.err.println(ret);
t.decoderbase64file(ret, "d://ghstest/retfile.docx", "d://ghstest/");
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
/**
   * 将文件转成base64 字符串
   *
   * @param path文件路径
   * @return *
   * @throws exception
   */
  public static string encodebase64file(string path) throws exception {
    file file = new file(path);
    fileinputstream inputfile = new fileinputstream(file);
    byte[] buffer = new byte[(int) file.length()];
    inputfile.read(buffer);
    inputfile.close();
    return new base64encoder().encode(buffer);
  }
  /**
   * 将base64字符解码保存文件
   *
   * @param base64code
   * @param targetpath
   * @throws exception
   */
  public static void decoderbase64file(string base64code, string targetpath,string catalogue)
      throws exception {
  file file = new file(catalogue);
  if(file.exists()==false){
  file.mkdirs();
  }
    byte[] buffer = new base64decoder().decodebuffer(base64code);
    fileoutputstream out = new fileoutputstream(targetpath);
    out.write(buffer);
    out.close();
  }
}

ps:这里再推荐几款加密解密相关在线工具供大家参考使用:

线编码转换工具(utf-8/utf-32/punycode/base64):

base64编码解码工具:

图片转换为base64编码在线工具:

在线md5/hash/sha-1/sha-2/sha-256/sha-512/sha-3/ripemd-160加密工具:

更多关于java相关内容感兴趣的读者可查看本站专题:《java数学运算技巧总结》、《java数据结构与算法教程》、《java字符与字符串操作技巧总结》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

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

相关文章:

验证码:
移动技术网