import sun.misc.BASE64Decoder;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class FileUtils {
private static final String filePathRoot = "D:\yzy";
public static String encryptToBase64(String filePath) {
if (filePath == null) {
return null;
}
try {
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Base64.getEncoder().encodeToString(data);
}
public static File getFileFromBase64(String base, String suffix) {
String base64Pic = base;
File file = null;
Map resultMap = new HashMap();
// 图像数据为空
if (base64Pic == null) {
resultMap.put("resultCode", 0);
resultMap.put("msg", "图片为空");
} else {
try {
BASE64Decoder decoder = new BASE64Decoder();
//前台在用Ajax传base64值的时候会把base64中的+换成空格,所以需要替换回来。
String baseValue = base64Pic.replaceAll(" ", "+");
//去除base64中无用的部分
byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));
base64Pic = base64Pic.replace("base64,", "");
String nowDateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String imgFilePath = filePathRoot + "\" + nowDateStr;
File file1 = new File(imgFilePath);
//判断文件路径下的文件夹是否存在,不存在则创建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
for (int i = 0; i < b.length; ++i) {
// 调整异常数据
if (b[i] < 0) {
b[i] += 256;
}
}
file = new File(imgFilePath + "\" + System.currentTimeMillis() + "." + suffix);
// 如果要返回file文件这边return就可以了,存到临时文件中
OutputStream out = new FileOutputStream(file.getPath());
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
resultMap.put("resultCode", 0);
resultMap.put("msg", "存储异常");
}
}
return file;
}
public static void download(String urlString, String filename) throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();
// base64转文件
String base64FromInputStream = getBase64FromInputStream(is);
// 获取图片的扩展名
String extensionName = filename.substring(filename.lastIndexOf(".") + 1);
getFileFromBase64(base64FromInputStream, extensionName);
}
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String url = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
String fileName = "sftp_test.png";
// String savePath = filePathRoot + "\testDownload";
download(url, fileName);
// 文件转Base64
String filePath = filePathRoot + "\testDownload\af4616c312d.png";
String dd = encryptToBase64(filePath);
System.out.println(dd);
System.out.println("---------------------------------------");
// Base64转文件
System.out.println("---------------------------------------" + filePath.substring(filePath.lastIndexOf(".") + 1));
getFileFromBase64(dd, filePath.substring(filePath.lastIndexOf(".") + 1));
}
}