微信后端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

449 lines
16 KiB

package com.ynxbd.common.helper.common;/*
* *
* @Project MicroWeb
* @Name FileUtil
* @Author 王绍全
* @Date 2020/4/14 下午10:21
* @Version v1.0.0
* @Copyright @ 2020 云南新八达科技有限公司 All rights reserved.
*/
import com.ynxbd.common.result.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import sun.security.action.GetPropertyAction;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
// 读取配置文件
@Slf4j
public class FileHelper {
final private static String PROJECT_NAME = "wx";
final private static String ROOT_PATH = System.getProperty("catalina.home") + "/webapps/" + PROJECT_NAME;
// 文件统一上传到uploadFile文件夹下
final private static String UPLOAD_FOLDER = "/upload/";
/**
* 读取文件内容
*
* @param filePath 文件路径
* @return 读取到的字符串内容
*/
public static String readFile(String filePath, boolean isRelative) {
if (isRelative) filePath = ROOT_PATH + filePath;
log.info("读取文件-{filePath:{}}", filePath);
File file = new File(filePath);
StringBuilder result = new StringBuilder();
if (file.exists()) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String str;
while ((str = br.readLine()) != null) {
result.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result.toString();
}
public static List<String> readLineToList(String path) {
List<String> dataList = new ArrayList<>();
try (InputStream is = FileHelper.class.getClassLoader().getResourceAsStream(path)) {
if (is == null) {
return dataList;
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (!"".equals(line)) {
dataList.add(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
/**
* 把字符串存入到文件
*
* @param data 写入的数据
* @param filePath 文件路径
* @param isDateFolder 是否按照日期划分存储
* @param isRelative 是否返回相对路径
* @return 写入成功返回路径,失败返回null
*/
public static String uploadFile(byte[] data, String filePath, boolean isDateFolder, boolean isRelative) {
String path = ROOT_PATH + UPLOAD_FOLDER + filePath; // 绝对路径
String relativePath = UPLOAD_FOLDER + filePath; // 相对路径
if (createFile(path, isDateFolder) == null) {
return null; // 创建失败
}
FileOutputStream out = null; // 文件输出流
try {
out = new FileOutputStream(path);
out.write(data);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info(isRelative ? "相对路径-{}" : "绝对路径-{}", relativePath, path);
return isRelative ? relativePath : path;
}
/**
* 修改文件名
*
* @param filePath 文件路径
* @param newFileName 新文件名
* @return 是否修改成功
*/
public static String updateFileName(String filePath, String newFileName) {
File oldFile = new File(filePath);
File folder = oldFile.getParentFile();
if (!folder.exists()) { // 目录不存在
if (!folder.mkdirs()) return null; // 创建目录失败
} else {
if (!folder.isDirectory()) return null; // 不是目录
}
String folderPath = oldFile.getParent(); // 文件夹路径
String suffix = filePath.substring(filePath.lastIndexOf("."));
String newFilePath = folderPath + "/" + newFileName + suffix;
File newFile = new File(newFilePath);
if (!newFile.exists()) { // 文件不存在
return oldFile.renameTo(newFile) ? newFilePath : null; // 成功返回新文件路径
} else {
String repeatPath = folderPath + "/repeat-" + System.currentTimeMillis() + suffix;
return oldFile.renameTo(new File(repeatPath)) ? repeatPath : null; // 文件重复
}
}
/**
* 创建文件
*
* @param filePath 文件路径,含有文件名
* @return 创建成功返回文件路径,创建失败返回null
*/
public static String createFile(String filePath, boolean isDateFolder) {
try {
File file = new File(filePath);
File folder;
if (isDateFolder) {
String parentPath = file.getParent();
String dateFolder = new SimpleDateFormat("yyyyMM").format(new Date());
folder = new File(parentPath + "/" + dateFolder);
} else {
folder = file.getParentFile(); // 获取文件夹路径
}
log.info("创建文件-{folder:{}, filePath:{}}", folder, filePath);
if (!folder.exists()) { // 目录不存在
if (!folder.mkdirs()) return null; // 创建目录失败
} else {
if (!folder.isDirectory()) return null; // 不是目录
}
if (!file.exists()) { // 文件不存在
return file.createNewFile() ? filePath : null; // 创建文件
} else {
return file.isFile() ? filePath : null; // 文件存在返回路径,不存在返回null
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 字符串写入文件
*
* @param content 存储字符串
* @param filePath 存储路径
* @param isRelative true,获取相对路径,false获取绝对路径
* @return 是否成功
*/
public static String uploadFile(String content, String filePath, Boolean isRelative) {
return saveStrToFile(content, filePath, isRelative, false);
}
/**
* 字符串写入文件
*
* @param content 存储字符串
* @param filePath 存储路径
* @param isRelative true,获取相对路径,false获取绝对路径
* @return 是否成功
*/
public static String updateFile(String content, String filePath, Boolean isRelative) {
return saveStrToFile(content, filePath, isRelative, false);
}
/**
* 字符串写入文件
*
* @param content 存储字符串
* @param folderName 存储路径
* @param fileName 文件名
* @param isRelative true,获取相对路径,false获取绝对路径
* @return 是否成功
*/
public static String saveStrToFile(String content, String folderName, String fileName, Boolean isRelative) {
String dateFolder = new SimpleDateFormat("yyyyMM").format(new Date());
String filePath = folderName + "/" + dateFolder + "/" + fileName;
return saveStrToFile(content, filePath, isRelative, false);
}
/**
* 字符串写入文件
*
* @param content 存储字符串
* @param filePath 存储路径
* @param isRelative true,获取相对路径,false获取绝对路径
* @param append true 在现有文件中继续添加内容, false 进行覆盖
* @return 是否成功
*/
public static String saveStrToFile(String content, String filePath, Boolean isRelative, Boolean append) {
String path = ROOT_PATH + UPLOAD_FOLDER + filePath; // 绝对路径
String relativePath = UPLOAD_FOLDER + filePath; // 相对路径
if (content == null) {
log.info("写入内容为空");
return null;
}
if (createFile(path, false) == null) return null; // 创建失败
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(path, append));
bw.write(content);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.info(isRelative ? "相对路径:{}" : "绝对路径:{}", relativePath, path);
return isRelative ? relativePath : path;
}
/**
* @param base64 base64数据
* @param folderName 文件夹名
* @param fileName 文件名
* @param isDateFolder 是否按照日期划分存储
* @param isRelative 是否返回相对路径
* @return 成功:返回文件路径,失败返回null
*/
public static String saveBase64Image(String base64, String folderName, String fileName, boolean isDateFolder, boolean isRelative) {
if (!base64.contains(",")) {
log.info("图片转码失败!");
return null;
}
// 前端在用Ajax传base64值的时候 ==>会把base64中的"+"换成空格,所以需要替换回来
String data = base64.substring(base64.indexOf(",") + 1).replaceAll(" ", "+");
byte[] decodedBytes;
try {
// BASE64Decoder base64Decoder = new BASE64Decoder();
// decodedBytes = base64Decoder.decodeBuffer(data);
decodedBytes = java.util.Base64.getDecoder().decode(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (decodedBytes == null) {
log.info("数据为空");
return null;
}
String filePath = folderName + "/" + fileName;
String idCardImgPath = FileHelper.uploadFile(decodedBytes, filePath, isDateFolder, isRelative);
if (idCardImgPath == null) { // 写入失败
log.info(("base64图片存储失败-{filePath:{}}"), filePath);
return null;
}
return idCardImgPath;
}
/**
* 通过支付宝查询对账单接口返回的url,下载zip文件
*
* @param downUrl 下载地址
* @param folderName 文件夹名称
* @param fileName 文件名
* @return 是否成功
*/
public static String downLoadZip(String downUrl, String folderName, String fileName) {
if (ObjectUtils.isEmpty(downUrl) || ObjectUtils.isEmpty(fileName)) {
return null;
}
InputStream in = null;
FileOutputStream out = null;
try {
File rootFile = new File(AccessController.doPrivileged(new GetPropertyAction("java.io.tmpdir")));
URLConnection conn = new URL(downUrl).openConnection();
in = conn.getInputStream();
if (ObjectUtils.isEmpty(folderName)) {
folderName = "order_zip";
} else {
if (folderName.contains("/") || folderName.contains("\\")) {
throw new ServiceException("文件夹名中不能含有斜杆");
}
}
String folderPath = rootFile.getAbsolutePath() + "\\" + folderName;
//自定义文件保存地址
File folder = new File(folderPath);//下载文件存放地址
if (!folder.exists()) { // 目录不存在
if (!folder.mkdirs()) {
return null;
}
} else {
if (!folder.isDirectory()) {
return null;
}
}
String filePath = folderPath + "\\" + fileName;
out = new FileOutputStream(filePath);
int read;
byte[] buffer = new byte[2048];
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
return filePath;
} catch (Exception e) {
ErrorHelper.println(e);
} finally {
try {
if (out != null) out.close();
if (in != null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 读取zip文件中的指定文件内容
*
* @param zipPath 压缩文件路径
* @param fileName 提取内容的文件名
* @param isDelete 是否删除文件
* @return 内容
*/
public static String readZip(String zipPath, String fileName, Charset charset, boolean isDelete) {
StringBuilder content = new StringBuilder();
if (ObjectUtils.isEmpty(zipPath) || ObjectUtils.isEmpty(fileName) || charset == null) {
return content.toString();
}
BufferedReader br = null;
ZipFile zipFile = null;
File file = null;
try {
file = new File(zipPath);
zipFile = new ZipFile(new File(zipPath), charset);
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
ZipEntry fileItem;
while (zipEntries.hasMoreElements()) {
fileItem = zipEntries.nextElement();
if (fileItem.getName().equals(fileName)) {
if (fileItem.getSize() == 0) {
return content.toString();
}
br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(fileItem), charset));
String line;
while ((line = br.readLine()) != null) {
content.append(line).append("\\\n");
}
}
}
} catch (Exception e) {
ErrorHelper.println(e);
} finally {
try {
if (br != null) br.close();
if (zipFile != null) zipFile.close();
if (isDelete && file != null && file.exists() && file.getName().contains(".zip")) {
log.info("临时文件[{}]清除 {}", fileName, (file.delete() ? "成功" : "失败"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return content.toString();
}
}