// resource目录下的文件名
String fileName = "static/apiclient_cert.p12";
// 获取系统类型名称
String os = System.getProperty("os.name");
try {
    // 判断Linux环境下与Windows环境下,获取密钥文件路径
    if (os != null && os.toLowerCase().startsWith("windows")) {
         path = new ClassPathResource(fileName).getURL().getPath();
    } else if (os != null && os.toLowerCase().startsWith("linux")) {
        path = FileUtil.getFileAbsolutePath(fileName);
    }
} catch (IOException e) {
    e.printStackTrace();
}

FileUtil工具类

package com.ruoyi.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
 
import java.io.File;
import java.io.InputStream;

@Slf4j
public class FileUtil {
    /**
     * linux下运行jar,通过路径获取文件的绝对路径
     * @param path  传相对路径 比如 cert/alipay/xxx.crt
     * @return  返回的路径就是放在linux服务器上的文件路径
     */
    public static String getFileAbsolutePath(String path){
        try {
            // 创建临时文件,获取jar里面的配置文件
            File file = new File("/home/file/" + path);
            if(file.exists()){
                return file.getAbsolutePath();
            }
            InputStream inputStream = null;
            try {
                ClassPathResource resource = new ClassPathResource(path);
                inputStream = resource.getInputStream();
                FileUtils.copyInputStreamToFile(inputStream, file);
                return file.getAbsolutePath();
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        } catch (Exception e) {
            log.error("FileUtil getFilePath Fail cause by:",e);
        }
        return null;
    }
}
Logo

更多推荐