package com.lxzn.framework.utils.file;
|
|
import com.lxzn.framework.domain.filesystem.response.FileUploadResult;
|
import com.lxzn.framework.domain.nc.response.DocumentCode;
|
import com.lxzn.framework.exception.ExceptionCast;
|
import com.lxzn.framework.utils.SHA256Util;
|
import com.lxzn.framework.utils.date.DateUtil;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.lang3.StringUtils;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.mock.web.MockMultipartFile;
|
import org.springframework.stereotype.Component;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import javax.servlet.http.HttpServletResponse;
|
import java.io.*;
|
import java.math.BigDecimal;
|
import java.net.URLEncoder;
|
import java.nio.ByteBuffer;
|
import java.nio.channels.FileChannel;
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.nio.file.Paths;
|
import java.nio.file.StandardCopyOption;
|
import java.security.MessageDigest;
|
import java.util.ArrayList;
|
import java.util.Date;
|
import java.util.List;
|
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipOutputStream;
|
|
@Slf4j
|
@Component
|
public class FileUtil {
|
|
private static String fileUploadFolder;
|
|
@Value("${fileHomePath}")
|
public void setFileUploadFolder(String fileUploadFolder) {
|
FileUtil.fileUploadFolder = fileUploadFolder;
|
}
|
|
|
private static String fileNcFolder;
|
|
@Value("${fileNCPath}")
|
public void setFileNCFolder(String fileNcFolder) {
|
FileUtil.fileNcFolder = fileNcFolder;
|
}
|
|
private static String addOrDelete;
|
|
@Value("${ncSend.addOrDelete}")
|
public void addOrDelete(String addOrDelete) {
|
FileUtil.addOrDelete = addOrDelete;
|
}
|
|
public static FileUploadResult uploadFileByFileNameAndFis(String fileName, InputStream fis) {
|
if(fis == null)
|
return null;
|
//String fileName = file.getName();
|
String suffix = getFileSuffix(fileName);
|
// if(StringUtils.isBlank(suffix))
|
// return null;
|
Date currentDate = DateUtil.getNow();
|
String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
|
//相对路径
|
String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
//绝对路径
|
String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
String fileNameNonSuffix = getFilenameNonSuffix(fileName);
|
if(fileNameNonSuffix == null) {
|
return null;
|
}
|
|
String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
|
//Long fileSize = fis;
|
long b = uploadFileByFis(fis, absolutePath, encodeFileName);
|
if(b <= 0)
|
return null;
|
FileUploadResult dto = new FileUploadResult();
|
dto.setFileName(fileNameNonSuffix);
|
dto.setEncodeFileName(encodeFileName);
|
dto.setFilePath(relativePath);
|
dto.setFileSize(b);
|
dto.setFileSuffix(suffix);
|
return dto;
|
}
|
/**
|
* 方法一:使用 FileWriter 写文件
|
* @param filepath 文件目录
|
* @param content 待写入内容
|
* @throws IOException
|
*/
|
public static void fileWriterSql(String filepath, String content) throws IOException {
|
OutputStreamWriter outputStreamWriter = null;
|
try {
|
File file = new File(filepath);
|
if (!file.exists()){
|
file.createNewFile();
|
}
|
FileOutputStream outputStream = new FileOutputStream(file);
|
if (outputStream != null){
|
outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
|
outputStreamWriter.write(content);
|
outputStreamWriter.flush();
|
}
|
}
|
catch (IOException e) {
|
e.getMessage();
|
}
|
finally {
|
try {
|
if (outputStreamWriter != null){
|
outputStreamWriter.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
|
public static boolean copyNcFile(String lastFile,String filePath) {
|
String absolutePathSend = lastFile;
|
FileChannel in = null;
|
FileChannel out = null;
|
try{
|
in = new FileInputStream(absolutePathSend).getChannel();
|
File file = new File(filePath);
|
if (!file.getParentFile().exists()){
|
//文件夹不存在 生成
|
file.getParentFile().mkdirs();
|
}
|
out = new FileOutputStream(filePath, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
try {
|
Thread.sleep(50);
|
} catch (InterruptedException e) {
|
e.printStackTrace();
|
}
|
in.close();
|
out.close();
|
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
try {
|
if (in != null) {
|
in.close();
|
}
|
if (out != null) {
|
out.close();
|
}
|
} catch (IOException e1) {
|
e1.printStackTrace();
|
}
|
return false;
|
}finally {
|
try {
|
if (in != null) {
|
in.close();
|
}
|
if (out != null) {
|
out.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return true;
|
}
|
|
/**
|
* 新建文件夹
|
* @param path
|
* @return
|
*/
|
|
public static boolean saveFileFromPath(String path) {
|
if (StringUtils.isEmpty(path)) {
|
return false;
|
}
|
String absolutePath = fileNcFolder + "/" + path ;
|
try {
|
boolean b = new File(absolutePath).mkdirs();
|
return b;
|
}catch (Exception e) {
|
return false;
|
}
|
}
|
|
/**
|
* 新建文件夹
|
* @param path
|
* @return
|
*/
|
|
public static boolean saveDeviceFromPath(String path) {
|
if (StringUtils.isEmpty(path)) {
|
return false;
|
}
|
String absolutePathSend = fileNcFolder + "/" + path + "/send" ;
|
String absolutePathRec = fileNcFolder + "/" + path + "/rec" ;
|
try {
|
boolean b = new File(absolutePathSend).mkdirs();
|
boolean c = new File(absolutePathRec).mkdirs();
|
return b;
|
}catch (Exception e) {
|
return false;
|
}
|
}
|
|
|
/**
|
* 修改文件夹
|
* @param path
|
* @return
|
*/
|
|
public static boolean updateFileFromPath(String path,String lastPathName) {
|
if (StringUtils.isEmpty(path)) {
|
return false;
|
}
|
String absolutePathLast = fileNcFolder + "/" + lastPathName ;
|
String absolutePathNew = fileNcFolder + "/" + path ;
|
try {
|
boolean b = new File(absolutePathLast).renameTo(new File(absolutePathNew));
|
return b;
|
}catch (Exception e) {
|
return false;
|
}
|
}
|
|
public static boolean uploadFileSend(MultipartFile file,String path) {
|
if(file == null || file.isEmpty()) {
|
return false;
|
}
|
//绝对路径
|
String absolutePath = fileNcFolder + "/" + path + "/send/";
|
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
|
// 目标文件路径+文件名
|
String targetFile = absolutePath + file.getOriginalFilename() ;
|
File toFile = new File(targetFile);
|
if (!toFile.getParentFile().exists()) {
|
toFile.mkdirs();
|
}
|
|
try {
|
file.transferTo(toFile);
|
} catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
return true;
|
}
|
/**
|
* file转MultipartFile
|
*
|
* @param file file
|
* @return MultipartFile
|
*/
|
public static MultipartFile fileToMultipartFile(File file) {
|
MultipartFile result = null;
|
if (null != file) {
|
try (FileInputStream input = new FileInputStream(file)) {
|
result = new MockMultipartFile(file.getName().concat("temp"), file.getName(), "text/plain", input);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return result;
|
}
|
|
public static boolean copyFileRec(String lastFile) {
|
String absolutePathSend = lastFile;
|
//字符串替换
|
String absolutePathSendNotFile = lastFile.replace("\\rec\\","\\bak_rec\\");
|
String fileNameNoPath = (new File(lastFile)).getName();
|
String suffix = getFileSuffix(fileNameNoPath);
|
Integer recNum = absolutePathSendNotFile.lastIndexOf(fileNameNoPath);
|
if (suffix == null) {
|
|
absolutePathSendNotFile = absolutePathSendNotFile.substring(0,recNum) + fileNameNoPath+ "-" +
|
DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL);
|
/* absolutePathSendNotFile = absolutePathSendNotFile.replace(fileNameNoPath,
|
fileNameNoPath + "-" +DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL));*/
|
} else {
|
String name = fileNameNoPath.replace("." + suffix,"");
|
absolutePathSendNotFile = absolutePathSendNotFile.substring(0,recNum) + name+ "-" +
|
DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL) + "." + suffix;
|
}
|
try{
|
FileChannel in = new FileInputStream(absolutePathSend).getChannel();
|
File file = new File(absolutePathSendNotFile);
|
if (!file.getParentFile().exists()){
|
//文件夹不存在 生成
|
file.getParentFile().mkdirs();
|
}
|
FileChannel out = new FileOutputStream(absolutePathSendNotFile, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
public static boolean fileRecDelete(String lastFile) {
|
String absolutePathSend = lastFile;
|
Path path = Paths.get(lastFile);
|
try {
|
System.gc();
|
Files.delete(path);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
try{
|
File file = new File(lastFile);
|
file.delete();
|
return true;
|
}
|
catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
public static Boolean deleteFile(File file) {
|
//判断文件不为null或文件目录存在
|
if (file == null || !file.exists()) {
|
System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
|
return false;
|
}
|
//获取目录下子文件
|
File[] files = file.listFiles();
|
//遍历该目录下的文件对象
|
for (File f : files) {
|
//判断子目录是否存在子目录,如果是文件则删除
|
if (f.isDirectory()) {
|
//递归删除目录下的文件
|
deleteFile(f);
|
} else {
|
//文件删除
|
f.delete();
|
//打印文件名
|
System.out.println("文件名:" + f.getName());
|
}
|
}
|
//文件夹删除
|
file.delete();
|
System.out.println("目录名:" + file.getName());
|
return true;
|
}
|
|
public static boolean copyFile(String lastFile, String newFile, String fileName) {
|
String absolutePathSend = fileNcFolder + "/" + newFile + "/send/" + fileName;
|
String absolutePathSendNotFile = fileNcFolder + "/" + newFile + "/send/";
|
String absolutePath = fileUploadFolder + "/" + lastFile+"/"+fileName;
|
|
// 检查源文件是否存在且是一个文件
|
File sourceFile = new File(absolutePath);
|
if (!sourceFile.exists() || !sourceFile.isFile()) {
|
System.err.println("源文件不存在或不是一个文件: " + absolutePath);
|
return false;
|
}
|
|
try {
|
// 创建目标目录
|
File toFile = new File(absolutePathSendNotFile);
|
if ("true".equals(addOrDelete)) {
|
deleteFile(toFile);
|
}
|
toFile.mkdirs();
|
|
// 使用 try-with-resources 确保资源正确关闭
|
try (FileChannel in = new FileInputStream(sourceFile).getChannel()) {
|
// 查询目标文件是否存在
|
File destFile = new File(absolutePathSend);
|
boolean flag = destFile.exists();
|
|
if (flag) {
|
// 文件存在就要删除文件
|
System.gc();
|
destFile.delete();
|
}
|
|
String suffix = FileUtil.getFileSuffix(fileName);
|
String newFileName = FileUtil.getFilenameNonSuffix(fileName);
|
String zip = fileNcFolder + "/" + newFile + "/send/" + newFileName + "/";
|
|
try (FileChannel out = new FileOutputStream(absolutePathSend, true).getChannel()) {
|
out.transferFrom(in, 0, in.size());
|
}
|
|
if (suffix != null && suffix.equals("zip")) {
|
try {
|
FileZipUtil.unZipFiles(absolutePathSend, zip);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
return true;
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
/**
|
* 删除文件
|
*
|
* @param filePath
|
* @return
|
*/
|
public static boolean deleteFile(String filePath) {
|
boolean flag = false;
|
File file = new File(filePath);
|
if (!file.exists()) {
|
return flag;
|
}
|
if (!file.isDirectory()) {
|
return flag;
|
}
|
String[] tempList = file.list();
|
File temp;
|
for (int i = 0; i < tempList.length; i++) {
|
if (filePath.endsWith(File.separator)) {
|
temp = new File(filePath + tempList[i]);
|
} else {
|
temp = new File(filePath + File.separator + tempList[i]);
|
}
|
if (temp.isFile()) {
|
temp.delete();
|
}
|
if (temp.isDirectory()) {
|
// 先删除文件夹里面的文件
|
deleteFile(filePath + "/" + tempList[i]);
|
// 再删除空文件夹
|
deleteFile(filePath + "/" + tempList[i]);
|
flag = true;
|
}
|
}
|
return flag;
|
}
|
|
|
/**
|
* 删除文件
|
*
|
* @param filePath
|
* @return
|
*/
|
public static boolean deleteNcFile(String filePath) {
|
boolean flag = false;
|
File file = new File(filePath);
|
if (!file.exists()) {
|
return flag;
|
}
|
boolean b = file.delete();
|
if (!b) {
|
System.out.println("文件删除失败: " + filePath);
|
}
|
return true;
|
}
|
|
/**
|
* 集成数据
|
* @param lastFile
|
* @param newFile
|
* @param zipString
|
* @return
|
*/
|
public static boolean copyFileNcIntegration(String lastFile ,String newFile,String zipString) {
|
String lastFileReName = fileNcFolder + "/" + lastFile ;
|
if (StringUtils.isNotBlank(zipString)) {
|
lastFileReName = lastFileReName + "." + zipString;
|
newFile = newFile + "." + zipString;
|
}
|
FileChannel in = null;
|
FileChannel out = null;
|
try{
|
in = new FileInputStream(lastFileReName).getChannel();
|
out = new FileOutputStream(newFile, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
} finally {
|
try {
|
in.close();
|
out.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
}
|
}
|
|
|
|
|
/**
|
* 测试 更换名字
|
* @param lastFile
|
* @param newFile
|
* @param
|
* @return
|
*/
|
public static boolean copyFileUpName(String lastFile, String newFile, String fixFileName, String ncFix) {
|
String lastFileReName = fileNcFolder + "/" + lastFile;
|
if (StringUtils.isNotBlank(fixFileName)) {
|
lastFileReName = lastFileReName + "." + fixFileName;
|
newFile = newFile + "." + ncFix;
|
}
|
try {
|
long beginTime = System.currentTimeMillis();
|
Path sourcePath = Paths.get(lastFileReName);
|
Path targetPath = Paths.get(newFile);
|
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
|
long endTime = System.currentTimeMillis();
|
log.info("拷贝文件所消耗的时间是:{} 毫秒", endTime - beginTime);
|
return true;
|
} catch (IOException e) {
|
log.error("文件复制失败,源文件: {}, 目标文件: {}", lastFileReName, newFile, e);
|
return false;
|
}
|
}
|
|
public static String fileSizeNC(String lastFile,String fileName){
|
String absolutePathSend = fileUploadFolder + "/" + lastFile + "/" + fileName;
|
File file = new File(absolutePathSend);
|
if (!file.exists()) {
|
return "0";
|
}
|
return String.valueOf(file.length());
|
}
|
|
|
/* 产品树到设备树 NC - 增强版(带MD5校验和智能重试) */
|
public static boolean copyFileNc(String lastFile, String newFile, String fileName,
|
String newFileName, String zipString) {
|
// 1. 路径规范化
|
String absolutePathSend = Paths.get(fileUploadFolder, lastFile, fileName).toString();
|
String sendFolder = Paths.get(fileNcFolder, newFile, "send").toString();
|
|
// 2. 创建目标文件夹
|
File folder = new File(sendFolder);
|
if (!folder.exists() && !folder.mkdirs()) {
|
log.error("无法创建目标文件夹: {}", sendFolder);
|
return false;
|
}
|
|
// 3. 目标文件路径(带后缀)
|
String abNewFileReName = Paths.get(sendFolder, newFileName).toString();
|
if (StringUtils.isNotBlank(zipString)) {
|
abNewFileReName += "." + zipString;
|
}
|
|
// 4. 获取源文件预期大小
|
long expectedSize = -1;
|
try {
|
File sourceFile = new File(absolutePathSend);
|
expectedSize = sourceFile.length();
|
log.info("文件复制: 源={}, 大小={}字节", absolutePathSend, expectedSize);
|
} catch (SecurityException e) {
|
log.error("无法访问源文件: {}", absolutePathSend, e);
|
return false;
|
}
|
|
// 5. 复制操作(最多重试3次)
|
int maxRetries = 3;
|
int attempt = 0;
|
boolean copySuccess = false;
|
|
while (attempt < maxRetries && !copySuccess) {
|
attempt++;
|
try {
|
log.info("---- 开始第{}次复制尝试 ----", attempt);
|
|
// 6. 执行复制操作
|
try (FileChannel in = new FileInputStream(absolutePathSend).getChannel();
|
FileChannel out = new FileOutputStream(abNewFileReName).getChannel()) {
|
out.transferFrom(in, 0, in.size());
|
}
|
|
// 7. 文件大小验证
|
File copiedFile = new File(abNewFileReName);
|
long actualSize = copiedFile.length();
|
|
if (expectedSize != actualSize) {
|
log.warn("大小不一致! 预期: {}B, 实际: {}B (差值: {}B)",
|
expectedSize, actualSize, Math.abs(actualSize - expectedSize));
|
|
} else {
|
log.info("文件大小验证成功: {}B", actualSize);
|
copySuccess = true;
|
}
|
|
// 9. MD5校验
|
if (copySuccess) {
|
String sourceMd5 = calculateMD5(absolutePathSend);
|
String targetMd5 = calculateMD5(abNewFileReName);
|
|
if (!sourceMd5.equals(targetMd5)) {
|
log.warn("MD5不一致! 源: {}, 目标: {}", sourceMd5, targetMd5);
|
|
// 针对图片中的特殊模式处理(.nc/.NC大小写问题)
|
if (isCaseSensitiveMismatch(absolutePathSend, abNewFileReName)) {
|
log.info("大小写差异,视为等效");
|
} else {
|
copySuccess = false;
|
}
|
} else {
|
log.info("MD5验证成功");
|
}
|
}
|
|
} catch (IOException | SecurityException e) {
|
log.error("第{}次复制失败", attempt, e);
|
}
|
|
// 10. 重试间隔处理
|
if (!copySuccess && attempt < maxRetries) {
|
try {
|
int delay = 200 * attempt; // 递增延迟:200ms, 400ms
|
log.info("等待 {}ms 后重试", delay);
|
Thread.sleep(delay);
|
} catch (InterruptedException ie) {
|
Thread.currentThread().interrupt();
|
}
|
}
|
}
|
|
// 11. 解压缩处理(仅当复制成功)
|
if (copySuccess && "zip".equalsIgnoreCase(zipString)) {
|
try {
|
String unzipFolder = Paths.get(sendFolder, newFileName).toString();
|
File unzipDir = new File(unzipFolder);
|
if (!unzipDir.exists() && !unzipDir.mkdir()) {
|
log.error("无法创建解压缩目录: {}", unzipFolder);
|
} else {
|
log.info("开始解压缩文件: {}", abNewFileReName);
|
FileZipUtil.unZipFiles(abNewFileReName, unzipFolder);
|
log.info("解压缩完成: {} 到 {}", newFileName, unzipFolder);
|
}
|
} catch (Exception e) {
|
log.error("解压缩失败: {}", abNewFileReName, e);
|
}
|
}
|
|
return copySuccess;
|
}
|
|
/**
|
* 大小写敏感检查(处理.nc和.NC大小写差异)
|
*/
|
private static boolean isCaseSensitiveMismatch(String source, String target) {
|
String sourceExt = source.substring(source.lastIndexOf('.') + 1);
|
String targetExt = target.substring(target.lastIndexOf('.') + 1);
|
|
return !sourceExt.equals(targetExt) &&
|
sourceExt.equalsIgnoreCase(targetExt);
|
}
|
|
|
/*保存过期的nc*/
|
public static boolean copyOldFileNc(String lastFile ,String newFile, String fileName,String newFileName,String zipString) {
|
String absolutePathSend = fileUploadFolder + "/" + lastFile + "/" + fileName;
|
//判断文件夹是否存在
|
File file = new File(fileNcFolder + "/" + newFile + "/");
|
if (!file.exists()) {
|
file.mkdirs();
|
}
|
String abNewFileReName = fileNcFolder + "/" + newFile + "/" + newFileName ;
|
if (StringUtils.isNotBlank(zipString)) {
|
abNewFileReName = abNewFileReName + "." + zipString;
|
}
|
String zip = fileNcFolder + "/" + newFile + "/" + newFileName + "/";
|
try{
|
FileChannel in = new FileInputStream(absolutePathSend).getChannel();
|
FileChannel out = new FileOutputStream(abNewFileReName, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
if (zipString.equals("zip")) {
|
try {
|
FileZipUtil.unZipFiles(abNewFileReName,zip);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
|
public static void compressFolder(File folder, String zipFilePath) throws IOException {
|
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
|
compressFolder(folder, folder.getName(), zipOut);
|
zipOut.close();
|
}
|
|
private static void compressFolder(File folder, String parentFolder, ZipOutputStream zipOut) throws IOException {
|
if (folder.isFile()) {
|
String filePath = folder.getPath();
|
String entryPath = filePath.substring(parentFolder.length() + 1);
|
ZipEntry zipEntry = new ZipEntry(entryPath);
|
zipOut.putNextEntry(zipEntry);
|
FileInputStream fileIn = new FileInputStream(filePath);
|
byte[] buffer = new byte[1024];
|
int bytesRead;
|
while ((bytesRead = fileIn.read(buffer)) != -1) {
|
zipOut.write(buffer, 0, bytesRead);
|
}
|
fileIn.close();
|
zipOut.closeEntry();
|
} else {
|
for (File file : folder.listFiles()) {
|
compressFolder(file, parentFolder, zipOut);
|
}
|
}
|
}
|
/*产品树到设备树 NC*/
|
public static boolean copyFileNcToBak(String newFile, String newFileName,String fixFileName) {
|
String stringDate = DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_STRING);
|
String absolutePathSend = null,abNewFileReName= null;
|
absolutePathSend = fileNcFolder + "/" + newFile + "/send/" + newFileName ;
|
abNewFileReName = fileNcFolder + "/" + newFile + "/send_bak/" + "/" +stringDate+ "/" + newFileName + "_" + DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL) ;
|
if (StringUtils.isNotBlank(fixFileName) ) {
|
if(!fixFileName.equals("zip")) {
|
absolutePathSend = absolutePathSend + "." + fixFileName ;
|
abNewFileReName = abNewFileReName + "." + fixFileName ;
|
} else {
|
copyFileBakZip(new File(absolutePathSend),new File(abNewFileReName));
|
return true;
|
}
|
}
|
File targetFile = new File(abNewFileReName);
|
if(!targetFile.getParentFile().exists()){
|
targetFile.getParentFile().mkdirs();
|
}
|
try{
|
FileChannel in = new FileInputStream(absolutePathSend).getChannel();
|
FileChannel out = new FileOutputStream(abNewFileReName, true).getChannel();
|
out.transferFrom(in, 0, in.size());
|
in.close();
|
out.close();
|
return true;
|
}
|
catch (IOException e) {
|
e.printStackTrace();
|
return false;
|
}
|
|
}
|
|
public static Boolean deletePathNameFile(File file) {
|
//判断文件不为null或文件目录存在
|
if (file == null || !file.exists()) {
|
System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
|
return false;
|
}
|
//获取目录下子文件
|
File[] files = file.listFiles();
|
//遍历该目录下的文件对象
|
for (File f : files) {
|
//判断子目录是否存在子目录,如果是文件则删除
|
if (f.isDirectory()) {
|
//递归删除目录下的文件
|
deletePathNameFile(f);
|
} else {
|
//文件删除
|
f.delete();
|
//打印文件名
|
System.out.println("文件名:" + f.getName());
|
}
|
}
|
//文件夹删除
|
file.delete();
|
return true;
|
}
|
|
|
public static Boolean deleteZipFromToSend(String newFile,String newFileName,String zipString) {
|
String abNewFileReName = fileNcFolder + "/" + newFile + "/send/" + newFileName ;
|
if (StringUtils.isNotBlank(zipString)) {
|
if (zipString.equals("zip")) {
|
abNewFileReName = abNewFileReName + "." + zipString;
|
return fileRecDelete(abNewFileReName);
|
}
|
}
|
return true;
|
}
|
|
public static Boolean deleteFilePathZip(String newFile,String newFileName,String zipString) {
|
String abNewFileReName = fileNcFolder + "/" + newFile + "/send/" + newFileName ;
|
//分类
|
if (StringUtils.isNotBlank(zipString)) {
|
//有问题
|
if (zipString.equals("zip")) {
|
String stringDate = DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_STRING);
|
String abNewFileReNameBak = fileNcFolder + "/" + newFile + "/send_bak/" + "/" +stringDate+ "/" + newFileName + "_" +
|
DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL) ;
|
copyFileBakZip(new File(abNewFileReName),new File(abNewFileReNameBak));
|
return deleteFile(new File(abNewFileReName));
|
}
|
abNewFileReName = abNewFileReName + "." + zipString;
|
}
|
copyFileNcToBak(newFile,newFileName,zipString);
|
return fileRecDelete(abNewFileReName);
|
}
|
|
public static void copyFileBakZip(File file, File target) {
|
target = new File(target, file.getName());
|
if (!target.exists()) {
|
target.mkdirs();
|
}
|
if (file.isDirectory()) {
|
File[] files = file.listFiles();
|
for (File f : files) {
|
if (f.isDirectory()) {
|
copyFileBakZip(f, target);
|
}
|
else {
|
copyFileDeleteZip(f, target);
|
}
|
}
|
} else {
|
copyFileDeleteZip(file, target);
|
}
|
}
|
|
public static void copyFileDeleteZip(File file, File directory) {
|
try {
|
FileInputStream input = new FileInputStream(file);
|
FileOutputStream output = new FileOutputStream(new File(directory, file.getName()));
|
byte[] buff = new byte[8192];
|
int len = -1;
|
while ((len = input.read(buff)) > -1) {
|
output.write(buff);
|
}
|
input.close();
|
output.close();
|
} catch (Exception e) {
|
|
}
|
}
|
|
|
//改名
|
public static FileUploadResult uploadFileUpdateFileName(MultipartFile file,String fileName ,String suffix) {
|
if(file == null || file.isEmpty())
|
return null;
|
Date currentDate = DateUtil.getNow();
|
String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
|
//相对路径
|
String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
//绝对路径
|
String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
String fileNameNonSuffix = getFilenameNonSuffix(fileName);
|
if(fileNameNonSuffix == null)
|
return null;
|
String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
|
Long fileSize = file.getSize();
|
boolean b = uploadFile(file, absolutePath, encodeFileName);
|
if(!b)
|
return null;
|
FileUploadResult dto = new FileUploadResult();
|
dto.setFileName(fileNameNonSuffix);
|
dto.setEncodeFileName(encodeFileName);
|
dto.setFilePath(relativePath);
|
dto.setFileSize(fileSize);
|
dto.setFileSuffix(suffix);
|
return dto;
|
}
|
|
public static boolean deleteFileNewRec(String filePath) {
|
boolean flag = false;
|
File file = new File(filePath);
|
if (!file.exists()) {
|
return flag;
|
}
|
boolean b = file.delete();
|
if (!b) {
|
try {
|
System.gc();
|
Path path = Paths.get(filePath);
|
Files.deleteIfExists(path);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return true;
|
}
|
|
|
public static FileUploadResult uploadFile(MultipartFile file) {
|
if(file == null || file.isEmpty())
|
return null;
|
String fileName = file.getOriginalFilename();
|
String suffix = getFileSuffix(fileName);
|
// if(StringUtils.isBlank(suffix))
|
// return null;
|
Date currentDate = DateUtil.getNow();
|
String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
|
//相对路径
|
String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
//绝对路径
|
String absolutePath = fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
|
String fileNameNonSuffix = getFilenameNonSuffix(fileName);
|
if(fileNameNonSuffix == null)
|
return null;
|
String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
|
Long fileSize = file.getSize();
|
boolean b = uploadFile(file, absolutePath, encodeFileName);
|
if(!b)
|
return null;
|
FileUploadResult dto = new FileUploadResult();
|
dto.setFileName(fileNameNonSuffix);
|
dto.setEncodeFileName(encodeFileName);
|
dto.setFilePath(relativePath);
|
dto.setFileSize(fileSize);
|
dto.setFileSuffix(suffix);
|
return dto;
|
}
|
|
public static void downLoadFile(HttpServletResponse response, String fileName, String filePath, String toFileName) {
|
String absolutePath = fileUploadFolder + filePath;
|
File file = new File(absolutePath , fileName);
|
if(file.exists()) {
|
byte[] buffer = new byte[1024];
|
FileInputStream fis = null;
|
BufferedInputStream bis = null;
|
try {
|
response.setHeader("Content-Type", "application/octet-stream;charset=utf-8"); // 告诉浏览器输出内容为流
|
//response.setHeader("Content-Disposition", "attachment;fileName="+ new String(toFileName.getBytes("UTF-8"),"ISO-8859-1"));
|
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(toFileName, "UTF-8"));
|
fis = new FileInputStream(file);
|
bis = new BufferedInputStream(fis);
|
OutputStream os = response.getOutputStream();
|
int i = bis.read(buffer);
|
while (i != -1) {
|
os.write(buffer, 0, i);
|
i = bis.read(buffer);
|
}
|
}catch (Exception e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
}finally {
|
if(bis != null) {
|
try {
|
bis.close();
|
} catch (IOException e) {
|
}
|
}
|
if(fis != null) {
|
try {
|
fis.close();
|
} catch (IOException e) {
|
}
|
}
|
}
|
}else {
|
ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST);
|
}
|
}
|
/**
|
* 上传文件工具类
|
* @param multipartFile
|
* @param path
|
* @param fileNewName 新的文件名
|
* @return
|
*/
|
public static boolean uploadFile(MultipartFile multipartFile, String path, String fileNewName) {
|
File targetFile = new File(path, fileNewName);
|
if(!targetFile.getParentFile().exists()){
|
targetFile.getParentFile().mkdirs();
|
}
|
try {
|
multipartFile.transferTo(targetFile);
|
return true;
|
} catch (Exception e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
return false;
|
}
|
}
|
|
public static long uploadFileByFis(InputStream fis, String path, String fileNewName) {
|
File targetFile = new File(path, fileNewName);
|
if(!targetFile.getParentFile().exists()){
|
targetFile.getParentFile().mkdirs();
|
}
|
try {
|
FileOutputStream fos = new FileOutputStream(targetFile);
|
//FileInputStream fis = new FileInputStream(file);
|
byte[] bytes = new byte[1024 * 4];
|
int index = 0;
|
long total = 0;
|
while ((index = fis.read(bytes)) != -1) {
|
fos.write(bytes, 0, index);
|
total =+ index;
|
}
|
fis.close();
|
fos.flush();
|
fos.close();
|
return total;
|
} catch (Exception e) {
|
log.error(e.getMessage());
|
}
|
return -1;
|
}
|
|
/**
|
/**
|
* 获取文件后缀 无后缀文件返回NULL
|
* @param fileName
|
* @return
|
*/
|
public static String getFileSuffix(String fileName) {
|
if (fileName.contains(".")) {
|
String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
|
return suffix;
|
}else {
|
return null;
|
}
|
|
}
|
|
/**
|
* 获取文件名 不带后缀和点号
|
* @param fileName
|
* @return
|
*/
|
public static String getFilenameNonSuffix(String fileName) {
|
if (fileName.contains(".")) {
|
String filename = fileName.substring(0, fileName.lastIndexOf('.'));
|
return filename;
|
}else {
|
return fileName;
|
}
|
|
}
|
|
public static List<String> readFile(String fileEncodeName, String filePath) {
|
String absolutePath = fileUploadFolder + filePath;
|
File file = new File(absolutePath , fileEncodeName);
|
if(!file.exists() || file.isDirectory())
|
ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST);
|
String charset = checkFileEncode(file);
|
if(charset == null)
|
ExceptionCast.cast(DocumentCode.DOC_PUBLISH_FILE_NOT_EXIST);
|
List<String> readList = new ArrayList<>();
|
String tempString = null;
|
BufferedReader reader = null;
|
try {
|
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
|
while ((tempString = reader.readLine()) != null) {
|
readList.add(tempString);
|
}
|
if(readList.isEmpty())
|
return null;
|
return readList;
|
} catch (Exception e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
return null;
|
} finally {
|
if(reader != null) {
|
try {
|
reader.close();
|
} catch (IOException e) {
|
log.error(e.getMessage(), e.getStackTrace());
|
}
|
}
|
}
|
}
|
|
private static String checkFileEncode(File file) {
|
String charset = "GBK";
|
byte[] first3Bytes = new byte[3];
|
BufferedInputStream bis = null;
|
try {
|
boolean checked = false;
|
bis = new BufferedInputStream(new FileInputStream(file));
|
bis.mark(0);
|
int read = bis.read(first3Bytes, 0, 3);
|
if (read == -1)
|
return charset;
|
if(first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE ) {
|
charset = "UTF-16LE";
|
checked = true;
|
}else if ( first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF ) {
|
charset = "UTF-16BE";
|
checked = true;
|
}else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF ) {
|
charset = "UTF-8";
|
checked = true;
|
}
|
bis.reset();
|
if (!checked) {
|
while ((read = bis.read()) != -1 ) {
|
if ( read >= 0xF0 )
|
break;
|
if ( 0x80 <= read && read <= 0xBF ) // 单独出现BF以下的,也算是GBK
|
break;
|
if ( 0xC0 <= read && read <= 0xDF ) {
|
read = bis.read();
|
if ( 0x80 <= read && read <= 0xBF ) // 双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GBK编码内
|
continue;
|
else
|
break;
|
} else if ( 0xE0 <= read && read <= 0xEF ) {
|
// 也有可能出错,但是几率较小
|
read = bis.read();
|
if ( 0x80 <= read && read <= 0xBF ) {
|
read = bis.read();
|
if ( 0x80 <= read && read <= 0xBF ) {
|
charset = "UTF-8";
|
break;
|
} else
|
break;
|
} else {
|
break;
|
}
|
}
|
}
|
}
|
return charset;
|
}catch (Exception e) {
|
return null;
|
}finally {
|
if(bis != null) {
|
try {
|
bis.close();
|
} catch (IOException e) {
|
}
|
}
|
}
|
|
}
|
|
public static String changeFileFormat(String flow) {
|
BigDecimal flows = new BigDecimal(flow);
|
if (flows.compareTo(new BigDecimal(0)) > 0 && flows.compareTo(new BigDecimal(1024)) < 0) {//小于1M
|
return flows.toString() + "B";
|
} else if(flows.compareTo(new BigDecimal(1024)) >= 0 && flows.compareTo(new BigDecimal(1048576)) < 0){
|
BigDecimal result = flows.divide(new BigDecimal(1024),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "KB";
|
} else if(flows.compareTo(new BigDecimal(1048576)) >= 0 && flows.compareTo(new BigDecimal(1073741824)) < 0){
|
BigDecimal result = flows.divide(new BigDecimal(1048576),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "MB";
|
} else if(flows.compareTo(new BigDecimal(1073741824)) >= 0 && flows.compareTo(new BigDecimal("1099511627776")) < 0){
|
BigDecimal result = flows.divide(new BigDecimal(1073741824),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "GB";
|
} else if(flows.compareTo(new BigDecimal("1099511627776")) >= 0 && flows.compareTo(new BigDecimal("1125899906842624")) < 0){
|
BigDecimal result = flows.divide(new BigDecimal("1099511627776"),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "TB";
|
} else if(flows.compareTo(new BigDecimal("1125899906842624")) >= 0){
|
BigDecimal result = flows.divide(new BigDecimal("1125899906842624"),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "PB";
|
}else {
|
return "0";
|
}
|
}
|
|
|
public static String changeFileFormatKb(String flow) {
|
BigDecimal flows = new BigDecimal(flow);
|
if (flows.compareTo(new BigDecimal(0)) > 0 && flows.compareTo(new BigDecimal(1024)) < 0) {//小于1M
|
return flows.toString() + "B";
|
} else if(flows.compareTo(new BigDecimal(1024)) >= 0){
|
BigDecimal result = flows.divide(new BigDecimal(1024),2,BigDecimal.ROUND_HALF_UP);
|
return result.toString() + "KB";
|
} else {
|
return "0";
|
}
|
}
|
|
public static String getFileAbsPath(String path, String fileName){
|
path = fileNcFolder+ path +"/send/";
|
File file = new File(path, fileName);
|
if(file.exists()){
|
return file.getAbsolutePath();
|
}
|
return null;
|
}
|
|
public static String calculateMD5(String filePath) {
|
try (InputStream is = Files.newInputStream(Paths.get(filePath))) {
|
MessageDigest md = MessageDigest.getInstance("MD5");
|
byte[] buffer = new byte[8192];
|
int read;
|
|
while ((read = is.read(buffer)) != -1) {
|
md.update(buffer, 0, read);
|
}
|
|
byte[] digest = md.digest();
|
StringBuilder sb = new StringBuilder();
|
for (byte b : digest) {
|
sb.append(String.format("%02x", b));
|
}
|
return sb.toString();
|
} catch (Exception e) {
|
throw new RuntimeException("计算MD5失败: " + filePath, e);
|
}
|
}
|
|
}
|