springboot打成jar包resources下文件的获取

import org.apache.poi.util.IOUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 复制jar包内文件到外面
 *
 * @author xxf
 * @date 2023/4/14
 */

public class FileCopyUtils {
    public static String getPath(String path) {
        //获取资源文件
        ClassPathResource resource = new ClassPathResource(path);
        InputStream fis = null;
        FileOutputStream out = null;
        try {
            //重新组装路径
            String pathName = getJarFilePath() + "/" + resource.getFilename();
            //获取资源文件流
            fis = resource.getInputStream();
            //获取输出的文件流
            out = new FileOutputStream(pathName);
            //将资源文件拷贝到与jar包同目录下
            IOUtils.copy(fis, out);
            return pathName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取jar包所在目录
     *
     * @date 2023/4/14
     */
    private static String getJarFilePath() {
        ApplicationHome home = new ApplicationHome(FileCopyUtils.class);
        File jarFile = home.getSource();
        return jarFile.getParentFile().toString();
    }
}

调用getPath方法需要传入一个资源的相对路径

 

 

 如图所示,例如:FeilCopyUtils.getPath("key/apiclient_key.pem")

我的这个工具类主要是为了获取这个文件的路径,jar包里面的路径不能被识别

所以,我将jar包里面的文件复制出来与jar包为同一目录。并将该文件全路径返回。

大家如果只需要获取文件流,没必要全部拷贝代码。

posted @ 2023-04-14 16:04  xxfcode  阅读(525)  评论(0编辑  收藏  举报