java:springboot项目文件中Resource目录下文件路径的获取

// 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;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值