浏览代码

图片同步完成

xujunwei 6 月之前
父节点
当前提交
38c6ca26c1
共有 1 个文件被更改,包括 75 次插入0 次删除
  1. 75 0
      framework-common/src/main/java/com/mrxu/framework/common/util/FileFunc.java

+ 75 - 0
framework-common/src/main/java/com/mrxu/framework/common/util/FileFunc.java

@@ -1,8 +1,19 @@
 package com.mrxu.framework.common.util;
 
+import lombok.SneakyThrows;
+
 import java.io.*;
 import java.net.HttpURLConnection;
 import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
 
 
 public class FileFunc {
@@ -220,4 +231,68 @@ public class FileFunc {
 		}
 		return res;
 	}
+
+	/**
+	 * 获取文件夹下的所有文件名
+	 * @param path
+	 * @return
+	 */
+	public static List<String> getFileNamesFromFolder(String path) {
+		List<String> fileNameList = new ArrayList<>();
+		File folder = new File(path);
+		if (folder.exists() && folder.isDirectory()) {
+			File[] files = folder.listFiles();
+			if (files != null) {
+				for (File file : files) {
+					if (file.isFile()) {
+						fileNameList.add(file.getName());
+					}
+				}
+			}
+		}
+		else {
+			throw new BusinessException("路径:"+path+"不存在或不是一个文件夹");
+		}
+		return fileNameList;
+	}
+
+	/**
+	 * 读取指定目录下的所有 .txt 文件,并将文件名和内容放入 Map
+	 */
+	@SneakyThrows
+	public static Map<String, String> readTxtFilesToMap(String pathStr) {
+		Path rootPath = Paths.get(pathStr);
+		Map<String, String> fileMap = new HashMap<>();
+		if (!Files.exists(rootPath)) {
+			throw new BusinessException("指定的路径不存在: " + pathStr);
+		}
+		if (!Files.isDirectory(rootPath)) {
+			throw new BusinessException("指定的路径不是一个文件夹: " + pathStr);
+		}
+		try (Stream<Path> walk = Files.walk(rootPath)) {
+			walk.filter(Files::isRegularFile)
+					.filter(p -> p.toString().endsWith(".txt"))
+					.forEach(path -> {
+						try {
+							String fileName = path.getFileName().toString();
+							String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
+							fileMap.put(fileName, content);
+						}
+						catch (IOException e) {
+							throw new BusinessException("无法读取文件: " + path + ", 错误: " + e.getMessage());
+						}
+					});
+		}
+		return fileMap;
+	}
+
+	public static void newFile(String path, String content) {
+		try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
+			writer.write(content);
+		} catch (IOException e) {
+			throw new BusinessException("文件写入异常"+e.getMessage());
+		}
+	}
+
+
 }