Преглед изворни кода

fix:文件读取支持jar包内部文件

hidewnd пре 1 месец
родитељ
комит
3f89e4c9d7

+ 23 - 13
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/config/ip2Regin/IPReginConfig.java

@@ -1,5 +1,6 @@
 package com.ytpm.lemonios.config.ip2Regin;
 
+import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.StrUtil;
 import org.lionsoul.ip2region.service.Config;
 import org.lionsoul.ip2region.service.Ip2Region;
@@ -8,11 +9,12 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
 
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
 import java.nio.file.Paths;
 
 /**
@@ -59,20 +61,28 @@ public class IPReginConfig {
     private File getRegionFile(String fileName) throws FileNotFoundException {
         String externalFilePath = Paths.get(System.getProperty("user.dir"), fileName).toString();
         File externalFile = new File(externalFilePath);
-        if (!externalFile.exists() || !externalFile.isFile()) {
-            Resource internalResource = new ClassPathResource(fileName);
-            if (internalResource.exists() && internalResource.isFile()) {
-                try {
-                    externalFile = internalResource.getFile();
-                } catch (IOException e) {
-                    throw new RuntimeException(e);
-                }
-            }
+        if (externalFile.exists() && externalFile.isFile()) {
+            return externalFile;
         }
-        if (!externalFile.exists()) {
-            throw new FileNotFoundException(StrUtil.format("文件不存在:{}", fileName));
+        // 2. 同级目录不存在,查找classpath资源(支持JAR包内部)
+        ClassPathResource internalResource = new ClassPathResource(fileName);
+        if (internalResource.exists()) {
+            try (InputStream inputStream = internalResource.getInputStream()) {
+                // 创建临时文件(前缀为文件名,后缀自动生成,默认存储在系统临时目录)
+                File tempFile = File.createTempFile(StrUtil.removeSuffix(fileName, "." + FileUtil.extName(fileName)),
+                        "." + FileUtil.extName(fileName));
+                // 将JAR内资源字节流写入临时文件
+                Files.copy(inputStream, tempFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
+                // 可选:设置临时文件在JVM退出时自动删除
+                tempFile.deleteOnExit();
+                return tempFile;
+            } catch (IOException e) {
+                throw new RuntimeException(StrUtil.format("JAR内资源转临时文件失败:{}", fileName), e);
+            }
         }
-        return externalFile;
+
+        // 3. 两者均不存在,抛出异常
+        throw new FileNotFoundException(StrUtil.format("文件/资源不存在:{}", fileName));
     }