linux运行java项目的jar包,获取Resources下资源文件路径(支付宝的公钥证书填路径问题)。

这篇博客介绍了如何解决在Linux环境下运行Java jar包时无法通过路径读取文件的问题。作者提出将资源文件读取为输入流并生成临时文件的方法,确保在多服务器场景下无需手动放置文件。此外,还提供了一个读取网络文件并保存到本地的辅助方法。
摘要由CSDN通过智能技术生成

发现把代码打成jar包之后,放在linux环境上运行,是无法通过路径去读取文件的。
一个解决方案就是把相对路径的资源读出流,生成一个文件放在linux环境上(多服务器的情况,不需要自己手动放文件上去),这样就能读文件路径了。

文件在项目里面放的位置:

代码如下:

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;

/**
 * @Author ckl
 * @Date 2022-09-24 16:41
 */
@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;
    }

/**
     * 读网络上的文件地址,上传到本地
     * @param url 如:https://www.baidu.com/xxx.crt  文件外网地址
     * @return
     */
    public static String uploadToLocalByUrl(String url){
        try {
            // 文件名
            String fileName = url.substring(url.lastIndexOf("/")+1);
            File file = new File("/home/file/" + fileName);
            if(file.exists()){
                return file.getAbsolutePath();
            }
            InputStream inputStream = null;
            try {
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
                inputStream = new ByteArrayInputStream(Objects.requireNonNull(response.getBody()));
                FileUtils.copyInputStreamToFile(inputStream, file);
                return file.getAbsolutePath();
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        } catch (Exception e) {
            log.error("PayFileUtil uploadToLocalByUrl Fail cause by:",e);
        }
        return null;
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值