|
@@ -0,0 +1,80 @@
|
|
|
|
+package com.rongwei.zhsw.system.utils;
|
|
|
|
+
|
|
|
|
+import org.springframework.core.io.ClassPathResource;
|
|
|
|
+
|
|
|
|
+import java.io.File;
|
|
|
|
+import java.io.FileNotFoundException;
|
|
|
|
+import java.io.IOException;
|
|
|
|
+import java.io.InputStream;
|
|
|
|
+import java.nio.file.Files;
|
|
|
|
+
|
|
|
|
+/**
|
|
|
|
+ * EnvironmentAwareResourceLoader class
|
|
|
|
+ *
|
|
|
|
+ * @author XH
|
|
|
|
+ * @date 2025/05/06
|
|
|
|
+ */
|
|
|
|
+public class EnvironmentAwareResourceLoader {
|
|
|
|
+ /**
|
|
|
|
+ * 智能加载资源(自动判断环境)
|
|
|
|
+ * @param relativePath 资源相对路径(如:temp/example.txt)
|
|
|
|
+ * @return 文件输入流
|
|
|
|
+ * @throws IOException
|
|
|
|
+ */
|
|
|
|
+ public static InputStream loadResource(String relativePath) throws IOException {
|
|
|
|
+ if (isRunningInJar()) {
|
|
|
|
+ // 服务器环境:从JAR同级目录加载
|
|
|
|
+ File jarDir = getJarDirectory();
|
|
|
|
+ File targetFile = new File(jarDir, relativePath);
|
|
|
|
+
|
|
|
|
+ if (!targetFile.exists()) {
|
|
|
|
+ throw new FileNotFoundException("服务器环境文件未找到: " + targetFile.getAbsolutePath());
|
|
|
|
+ }
|
|
|
|
+ return Files.newInputStream(targetFile.toPath());
|
|
|
|
+
|
|
|
|
+ } else {
|
|
|
|
+ // 开发环境:从resources目录加载
|
|
|
|
+ ClassPathResource classPathResource = new ClassPathResource(relativePath);
|
|
|
|
+ return classPathResource.getInputStream();
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 判断是否运行在JAR包中
|
|
|
|
+ */
|
|
|
|
+ private static boolean isRunningInJar() {
|
|
|
|
+ try {
|
|
|
|
+ String path = EnvironmentAwareResourceLoader.class
|
|
|
|
+ .getProtectionDomain()
|
|
|
|
+ .getCodeSource()
|
|
|
|
+ .getLocation()
|
|
|
|
+ .toURI()
|
|
|
|
+ .getPath();
|
|
|
|
+
|
|
|
|
+ return path.contains(".jar!");
|
|
|
|
+ } catch (Exception e) {
|
|
|
|
+ return false; // 异常情况默认视为开发环境
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 获取JAR所在目录(仅在JAR运行时有效)
|
|
|
|
+ */
|
|
|
|
+ private static File getJarDirectory() {
|
|
|
|
+ try {
|
|
|
|
+ String jarPath = EnvironmentAwareResourceLoader.class
|
|
|
|
+ .getProtectionDomain()
|
|
|
|
+ .getCodeSource()
|
|
|
|
+ .getLocation()
|
|
|
|
+ .toURI()
|
|
|
|
+ .getPath();
|
|
|
|
+
|
|
|
|
+ String decodedPath = java.net.URLDecoder.decode(jarPath, String.valueOf(java.nio.charset.StandardCharsets.UTF_8));
|
|
|
|
+ File jarFile = new File(decodedPath);
|
|
|
|
+ return jarFile.getParentFile();
|
|
|
|
+
|
|
|
|
+ } catch (Exception e) {
|
|
|
|
+ throw new RuntimeException("获取JAR路径失败", e);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|