Java获取ClassPath下的预存文件

一 背景

        在以前的单体应用中我们可以将文件存放在服务器中的指定目录,然后通过代码直接获取,而当我们在使用Docker容器发布的时候,由于每次镜像打包都会将文件清除(本人目前的理解),而挂载目录使用不是很熟练(我的理解挂载目录可以解决),所以通过下列方式来实现ClassPath下预存文件处理。

二 示例分析

        直接向ClassPath目录下的文件读成文件流

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
try {
       Resource resource = new ClassPathResource("/cert/**/wxjsapiapiclient_cert.p12");
       File sourceFile = resource.getFile();
       InputStream certStream = new FileInputStream(sourceFile);
       this.certData = new byte[(int) sourceFile.length()];
       certStream.read(this.certData);
       certStream.close();
     } catch (Exception e) {
       System.err.print(e);
     }

        获取当前项目所在的绝对路径。

String path = System.getProperty("user.dir");

        获取当前项目中,某相对路径下资源的绝对路径。

/**
 * @author calm_encode
 */
public class ClassPathUtil {

    public String getClassPath(String relativePath){

        //获取ClassPath, relativePath 为资源的相对路径
        String path = ClassLoader.getSystemResource(relativePath).getPath();
        return path;
    }
}

三 完整示例

String path = System.getProperty("user.dir");
System.out.println("path = " + path);

String paths = ClassLoader.getSystemResource("common-images/photoBook/back_cover.png").getPath();
System.out.println(paths);

        结果:

         个人使用的一些方式,希望对各位有用。后续完全理解挂载目录和Docker镜像容器细节再来完善。待续。。。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值