package com.unnet.yjs.util;
import com.xiaoleilu.hutool.codec.Base64;
import com.xiaoleilu.hutool.date.DateUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.Date;
/**
* Email: love1208tt@foxmail.com
* Copyright (c) 2019. missbe
* @author lyg 19-7-9 下午7:22
*
* 文件和Base64互转工具
**/
public class Base64Util {
/**
* BASE64解密
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* BASE64加密
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
/**
* base64字符串转文件
*/
public static File base64ToFile(String base64) {
File file = null;
String fileName = DateUtil.format(new Date(),"yyyyMMddhhmmss")+System.currentTimeMillis();
FileOutputStream out = null;
try {
// 解码,然后将字节转换为文件
file = new File(fileName);
if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
}
// 将字符串转换为byte数组
byte[] bytes = Base64.decode(base64,"utf-8");
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
byte[] buffer = new byte[1024];
out = new FileOutputStream(file);
int byteread;
while ((byteread = in.read(buffer)) != -1) {
// 文件写操作
out.write(buffer, 0, byteread);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (out!= null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
/**
* 文件转base64字符串
*/
public static String fileToBase64(File file) {
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(file);
byte[] bytes = new byte[in.available()];
int length = in.read(bytes);
//encodeToString(bytes, 0, length, Base64.DEFAULT);
base64 = Base64.encode(bytes, "utf-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return base64;
}
}
网友评论