From 30c9299fa9ffc8d3cd51d4a18b4c0b33c3ef8141 Mon Sep 17 00:00:00 2001
From: lyh <925863403@qq.com>
Date: 星期三, 08 四月 2026 09:36:44 +0800
Subject: [PATCH] 修改
---
src/main/java/com/lxzn/framework/utils/file/FileUtil.java | 288 +++++++++++++++++++++++++++++++++------------------------
1 files changed, 168 insertions(+), 120 deletions(-)
diff --git a/src/main/java/com/lxzn/framework/utils/file/FileUtil.java b/src/main/java/com/lxzn/framework/utils/file/FileUtil.java
index a7994d9..e20959e 100644
--- a/src/main/java/com/lxzn/framework/utils/file/FileUtil.java
+++ b/src/main/java/com/lxzn/framework/utils/file/FileUtil.java
@@ -5,7 +5,6 @@
import com.lxzn.framework.exception.ExceptionCast;
import com.lxzn.framework.utils.SHA256Util;
import com.lxzn.framework.utils.date.DateUtil;
-import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
@@ -17,8 +16,9 @@
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
-import java.security.MessageDigest;
+import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -28,6 +28,7 @@
public class FileUtil {
private static String fileUploadFolder;
+
@Value("${fileHomePath}")
public void setFileUploadFolder(String fileUploadFolder) {
@@ -62,6 +63,91 @@
dto.setFileSize(fileSize);
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();
+ }
+ try {
+ if (outputStreamWriter != null){
+ outputStreamWriter.close();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ catch (IOException e) {
+ e.getMessage();
+ }
+ finally {
+ try {
+ if (outputStreamWriter != null){
+ outputStreamWriter.close();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * 鍒犻櫎鏂囦欢
+ *
+ * @param filePath
+ * @return
+ */
+ public static boolean deleteNcFile(String filePath) {
+ String lastFileReName = fileUploadFolder + "/" + filePath ;
+ boolean flag = false;
+ File file = new File(lastFileReName);
+ if (!file.exists()) {
+ return flag;
+ }
+ boolean b = file.delete();
+ if (!b) {
+ System.out.println("鏂囦欢鍒犻櫎澶辫触锛� " + filePath);
+ }
+ return true;
+ }
+
+ public static boolean copyFileUpName(String lastFile ,String newFile,String ncFix) {
+ String lastFileReName = fileUploadFolder + "/" + lastFile ;
+ if (StringUtils.isNotBlank(ncFix)) {
+ newFile = newFile + "." + ncFix;
+ }
+ File toFile = new File(newFile);
+ if (!toFile.getParentFile().exists()) {
+ toFile.mkdirs();
+ }
+ try {
+ long begintime = System.currentTimeMillis(); // 鑾峰彇鎷疯礉鏂囦欢鍓嶇殑绯荤粺鏃堕棿
+ Files.copy(Paths.get(lastFileReName),
+ Paths.get(newFile),
+ StandardCopyOption.REPLACE_EXISTING);
+ long endtime = System.currentTimeMillis(); // 鑾峰彇鏂囦欢鎷疯礉缁撴潫鏃剁殑绯荤粺鏃堕棿
+ System.out.println("鎷疯礉鏂囦欢鎵�娑堣�楃殑鏃堕棿鏄細" + (endtime - begintime) + "姣");
+ return true;
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
}
public static FileUploadResult uploadFile(String fileName, InputStream fis) {
@@ -179,6 +265,54 @@
log.error(e.getMessage());
}
return -1;
+ }
+
+
+
+ /**
+ * 鍒犻櫎鏂囦欢
+ *
+ * @param filePath
+ * @return
+ */
+ public static boolean deleteFile(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;
+ }
+
+
+ /**
+ *
+ * @param file
+ * @return
+ */
+ public static long selectFileSize(File file) {
+ try (FileInputStream fis = new FileInputStream(file)) {
+ long size = 0;
+ int read;
+ byte[] buffer = new byte[1024];
+ while ((read = fis.read(buffer)) != -1) {
+ size += read;
+ }
+ return size;
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return 0;
}
/**
@@ -309,135 +443,42 @@
}
/**
- * 澶嶅埗鏂囦欢锛堝甫閲嶈瘯鍜屾牎楠�-闃叉涓鏂瑰痉澶嶅埗鏂囦欢鍑洪敊闂锛�
+ * 澶嶅埗鏂囦欢
* @param oldPath
* @param newPath
* @param fileName
*/
public static boolean copyFile(String oldPath, String newPath, String fileName){
- // 1. 璺緞瑙勮寖鍖�
- String absolutePathSend = fileUploadFolder + oldPath;
- String absolutePathTarget = fileUploadFolder + newPath;
-
- // 2. 鍒涘缓鐩爣鏂囦欢澶�
- File targetFolder = new File(absolutePathTarget);
- if (!targetFolder.exists() && !targetFolder.mkdirs()) {
- log.error("鏃犳硶鍒涘缓鐩爣鏂囦欢澶�: {}", absolutePathTarget);
- return false;
- }
-
- // 3. 婧愭枃浠跺拰鐩爣鏂囦欢璺緞
- String sourceFilePath = absolutePathSend + File.separator + fileName;
- String targetFilePath = absolutePathTarget + File.separator + fileName;
-
- // 4. 鑾峰彇婧愭枃浠堕鏈熷ぇ灏�
- long expectedSize = -1;
- File sourceFile = new File(sourceFilePath);
- if (!sourceFile.exists()) {
- log.error("婧愭枃浠朵笉瀛樺湪: {}", sourceFilePath);
- return false;
- }
-
- try {
- expectedSize = sourceFile.length();
- log.info("鏂囦欢澶嶅埗: 婧�={}, 鐩爣={}, 澶у皬={}瀛楄妭", sourceFilePath, targetFilePath, expectedSize);
- } catch (SecurityException e) {
- log.error("鏃犳硶璁块棶婧愭枃浠�: {}", sourceFilePath, 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(sourceFilePath).getChannel();
- FileChannel out = new FileOutputStream(targetFilePath).getChannel()) {
- out.transferFrom(in, 0, in.size());
- }
-
- // 7. 鏂囦欢澶у皬楠岃瘉
- File copiedFile = new File(targetFilePath);
- 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;
- }
-
- // 8. MD5鏍¢獙
- if (copySuccess) {
- String sourceMd5 = calculateMD5(sourceFilePath);
- String targetMd5 = calculateMD5(targetFilePath);
-
- if (!sourceMd5.equals(targetMd5)) {
- log.warn("MD5涓嶄竴鑷�! 婧�: {}, 鐩爣: {}", sourceMd5, targetMd5);
- copySuccess = false;
- } else {
- log.info("MD5楠岃瘉鎴愬姛");
- }
- }
-
- } catch (IOException | SecurityException e) {
- log.error("绗瑊}娆″鍒跺け璐�", attempt, e);
+ oldPath = fileUploadFolder + oldPath;
+ newPath = fileUploadFolder + newPath;
+ File oldFile = new File(oldPath, fileName);
+ File newFile = new File(newPath, fileName);
+ if(oldFile.exists()){
+ if(!newFile.getParentFile().exists()){
+ newFile.getParentFile().mkdirs();
}
-
- // 9. 閲嶈瘯闂撮殧澶勭悊
- if (!copySuccess && attempt < maxRetries) {
+ FileChannel inputChannel = null;
+ FileChannel outputChannel = null;
+ try{
+ inputChannel = new FileInputStream(oldFile).getChannel();
+ outputChannel = new FileOutputStream(newFile).getChannel();
+ outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
+ return true;
+ }catch (Exception e){
+ log.error("澶嶅埗鏂囦欢閿欒{}", e);
+ return false;
+ }finally {
try {
- int delay = 200 * attempt; // 閫掑寤惰繜锛�200ms, 400ms
- log.info("绛夊緟 {}ms 鍚庨噸璇�", delay);
- Thread.sleep(delay);
- } catch (InterruptedException ie) {
- Thread.currentThread().interrupt();
+ inputChannel.close();
+ outputChannel.close();
+ }catch (Exception e){
+ log.error("澶嶅埗鏂囦欢閿欒{}", e);
}
+
}
}
-
- if (copySuccess) {
- log.info("鏂囦欢澶嶅埗瀹屾垚: {}", targetFilePath);
- } else {
- log.error("鏂囦欢澶嶅埗澶辫触锛屽凡灏濊瘯{}娆�", maxRetries);
- }
-
- return copySuccess;
+ return false;
}
-
- /**
- * 璁$畻鏂囦欢鐨凪D5鍊�
- * @param filePath
- * @return
- */
- 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);
- }
- }
-
public static String getFileAbsPath(String path, String fileName){
path = fileUploadFolder + path;
@@ -448,5 +489,12 @@
return null;
}
+ public static String getFileAbsPathTxt(String path){
+ File file = new File(path);
+ if(file.exists()){
+ return file.getAbsolutePath();
+ }
+ return null;
+ }
}
--
Gitblit v1.9.3