|
|
@@ -0,0 +1,85 @@
|
|
|
+package com.ytpm.util;
|
|
|
+
|
|
|
+
|
|
|
+import org.springframework.core.io.ClassPathResource;
|
|
|
+import org.springframework.core.io.Resource;
|
|
|
+import org.springframework.util.FileCopyUtils;
|
|
|
+
|
|
|
+import java.io.File;
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStreamReader;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.nio.file.Files;
|
|
|
+import java.nio.file.Paths;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.List;
|
|
|
+import java.util.stream.Collectors;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @author lih
|
|
|
+ * @date 2025-11-11 13:31
|
|
|
+ */
|
|
|
+public class ResourceUtils {
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 优先读取JAR同级目录slogans.txt,不存在则读取resource目录
|
|
|
+ *
|
|
|
+ * @return 每行内容的List<String>(过滤空行)
|
|
|
+ * @throws IOException 外部和内部文件均读取失败时抛出
|
|
|
+ */
|
|
|
+ public static List<String> readFileToList(String fileName) throws IOException {
|
|
|
+ // 1. 构造JAR同级目录的外部文件路径
|
|
|
+ // user.dir = JAR所在的同级目录(执行java -jar命令的目录)
|
|
|
+ String externalFilePath = Paths.get(System.getProperty("user.dir"), fileName).toString();
|
|
|
+ File externalFile = new File(externalFilePath);
|
|
|
+
|
|
|
+ // 2. 优先读取外部文件(存在且可读)
|
|
|
+ if (externalFile.exists() && externalFile.canRead()) {
|
|
|
+ try {
|
|
|
+ return readFileToList(externalFile);
|
|
|
+ } catch (IOException e) {
|
|
|
+ // 外部文件存在但读取失败(如权限不足),降级读取内部文件
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 3. 读取内部resource目录文件(兜底方案)
|
|
|
+ Resource internalResource = new ClassPathResource(fileName);
|
|
|
+ if (!internalResource.exists()) {
|
|
|
+ throw new IOException("外部文件(" + externalFilePath + ")和内部resource文件均不存在");
|
|
|
+ }
|
|
|
+ return readFileToList(internalResource);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 读取本地File文件转为List<String>
|
|
|
+ */
|
|
|
+ private static List<String> readFileToList(File file) throws IOException {
|
|
|
+ try (InputStreamReader reader = new InputStreamReader(
|
|
|
+ Files.newInputStream(file.toPath()), StandardCharsets.UTF_8)) {
|
|
|
+ String content = FileCopyUtils.copyToString(reader);
|
|
|
+ return processContent(content);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 读取resource目录文件转为List<String>
|
|
|
+ */
|
|
|
+ private static List<String> readFileToList(Resource resource) throws IOException {
|
|
|
+ try (InputStreamReader reader = new InputStreamReader(
|
|
|
+ resource.getInputStream(), StandardCharsets.UTF_8)) {
|
|
|
+ String content = FileCopyUtils.copyToString(reader);
|
|
|
+ return processContent(content);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 处理文件内容:分割换行符、过滤空行、去除前后空白
|
|
|
+ */
|
|
|
+ private static List<String> processContent(String content) {
|
|
|
+ return Arrays.stream(content.split("\\r?\\n")) // 兼容Windows/Linux换行符
|
|
|
+ .map(String::trim) // 去除每行前后空白(可选)
|
|
|
+ .filter(line -> !line.isEmpty()) // 过滤空行(可选)
|
|
|
+ .collect(Collectors.toList());
|
|
|
+ }
|
|
|
+}
|