工作小总结

【已解决】Spring boot项目获取到resource目录下文件完整路径怎么获取 ?

在实际开发过程中,可能有时候,我们将文件放在resource下,在程序中需要获取到文件路径然后操作。比如,将公钥放到resource文件夹下,在程序中需要获取到这个公钥的完整路径。怎么操作?

在实际开发过程中,可能有时候,我们将文件放在resource下,在程序中需要获取到文件路径然后操作。比如,将公钥放到resource文件夹下,在程序中需要获取到这个公钥的完整路径。怎么操作?

feaa1926f7309d99289b71ee63e6607f.png

需要访问的文件位置


获取方法如下:

在yaml文件中配置公钥文件名称:

pem:
  public-key: publickey.pem

代码中获取公钥的绝对路径:

package com.kaigejava.config.pem;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.net.URL;


/**
 * @author kaigejava
 * @since 2023/6/27 9:48
 */
@Slf4j
@Data
public class PemBean {

    /**
     * 公钥名称
     */
    private static String pubKey = "publickey.pem";
    /**
     * 公钥地址
     */
    private static String pubKeyFilePath = "files/pem/";
    /**
     * zip文件地址
     */
    private static String zipDataBasePath = "files/zip/";

  

    public static String getPublicKey() {
        try {
            return function1(pubKey);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pubKey;
    }


    private static String getPrePath(String fileName, String path) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        URL fileUrl = classPathResource.getURL();
        // 获取文件的绝对路径
        String absolutePath = fileUrl.getPath();
        //本地运行的
        int index = -1;
		//

原创不易,完成人机校验,阅读全文

相关推荐