java 如何读取 jar 中的文件资源和路径

问题描述:项目需要将生成的文本存储在运行环境中,当我用相对路径 safe/certificate.pem存储时,出现了两种情况:

第一种:用idea启动项目
这时生成的文本会在编译后的 target.classes下创建对应目录,这时用百度上千篇一律的如下代码可以成功读取。问题的关键在于直接用idea启动的不是项目编译后的jar包 !

 public String getCert() {
        java.net.URL fileURL = this.getClass().getResource("/safe/certificate.pem");
        if (fileURL == null) {
            return "没有读取到证书!";
        }
        File file = new File(fileURL.getPath());
        long filelength = file.length();
        byte[] filecontent = new byte[(int) filelength];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(filecontent);
    }

请添加图片描述
第二种:用cmd 运行jar 包启动项目
通过jar运行的项目,会在jar包存储路径中生成jar同名文件,此时相对路径safe/certificate.pem生成的文本会在 jar 同名文件目录下创建对应目录,如下图蓝色框内容,这时通过上述的代码this.getClass().getResource(文件名)是获取不到文件的,会是null请添加图片描述
解决办法

  1. 得到 jar 文件路径
 String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
 
 //path : file:/C:/Users/Mr.Tan/Documents/IT/work/HB/danger-backend/danger-client/cipher-client/target/cipher-client.jar!/BOOT-INF/classes!/
  1. 解决可能存在的乱码
 String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
 try {
            path = java.net.URLDecoder.decode(path, "UTF-8");
            log.info("utf-8 path: " + path);
        } catch (java.io.UnsupportedEncodingException ex) {
            log.error(ex.getLocalizedMessage());
        }
        
// utf-8 path: file:/C:/Users/Mr.Tan/Documents/IT/work/HB/danger-backend/danger-client/cipher-client/target/cipher-client.jar!/BOOT-INF/classes!/        
  1. 获取绝对路径
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
        log.info("path: " + path);
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8");
            log.info("utf-8 path: " + path);
        } catch (java.io.UnsupportedEncodingException ex) {
            log.error(ex.getLocalizedMessage());

        }
        java.io.File jarFile = new java.io.File(path);
        log.info("jarFilepath: "+jarFile.getAbsolutePath() );

//jarFilepath:  C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\file:\C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\cipher-client.jar!\BOOT-INF\classes!
  1. 获取上一级文件
java.io.File parent = jarFile.getParentFile();
        log.info("parent: "+parent.getName());
        log.info(parent.getAbsolutePath());

// parent: BOOT-INF
// C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\file:\C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\cipher-client.jar!\BOOT-INF

参考代码
将生成的文件存到获取的绝对路径中,读取时从绝对路径读,将文件存在filet目录的上级目录,
在这里插入图片描述

	/**
     * 获取jar包中的绝对路径
     *
     * @return java.lang.String
     * @author luce
     * @date 2021/9/7 15:24
     */
    private String acquireJarPath() {
    	//jar包编译后的相对路径
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
        //消除乱码
        try {
            path = java.net.URLDecoder.decode(path, "UTF-8");
        } catch (java.io.UnsupportedEncodingException ex) {
            log.error(ex.getLocalizedMessage());
        }
        //根据路径获取目标文件
        java.io.File jarFile = new java.io.File(path);
        //获取文件的绝对路径
        String jarFilepath = jarFile.getAbsolutePath();
        //输出内容://jarFilepath:  C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\file:\C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\cipher-client.jar!\BOOT-INF\classes!
        //我们需要得到 file 的上级目录
        int end = jarFilepath.indexOf("file");
        if (end > 0) {
            return jarFilepath.substring(0, end);
            //输出结果:C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\
        }
        return jarFilepath + "\\";
    }


	/**
     * 存证书文件
     *
     * @param x509Certificate 证书
     * @param certStoragePath 存储路径 ->  C:\Users\Mr.Tan\Documents\IT\work\HB\cipher\target\safe\certificate.pem
     * @author luce
     * @date 2021/8/31 15:27
     */
    public static void createCert(X509Certificate x509Certificate, String certStoragePath) throws CertificateEncodingException {
    	//先删除,预防在原有文本中续写
        FileUtil.del(acquireJarPath() + "safe/certificate.pem");
        //在指定目录生成证书文件
        FileUtil.newFile(certStoragePath);
        //证书标题
        FileUtil.appendUtf8String(BEGIN_CERT, certStoragePath);
        //分割线
        FileUtil.appendUtf8String(System.getProperty("line.separator"), certStoragePath);
        //转Base64码的证书
        FileUtil.appendUtf8String(Base64Encoder.encode(x509Certificate.getEncoded()), certStoragePath);
        //分割线
        FileUtil.appendUtf8String(System.getProperty("line.separator"), certStoragePath);
        //尾文
        FileUtil.appendUtf8String(END_CERT, certStoragePath);
    }


	/**
     * 读取证书
     *
     * @return java.lang.String
     * @author luce
     * @date 2021/9/3 10:09
     */
    public String getCert() {
        File file = new File(acquireJarPath() + "safe/certificate.pem");
        //读取的路径:C:\Users\Mr.Tan\Documents\IT\work\HB\danger-backend\danger-client\cipher-client\target\safe/certificate.pem
        long filelength = file.length();
        byte[] filecontent = new byte[(int) filelength];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(filecontent);
    }
    
  • 8
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java -jar 配置文件是指使用Java命令来启动Java程序,并通过配置文件来指定程序的一些特定参数和配置信息。通常情况下,Java程序是通过命令行来启动的,而使用Java -jar命令则是一种更加便捷和灵活的方式。 Java -jar命令需要指定程序的jar路径,通过该jar的MANIFEST.MF文件定义的Main-Class来确定程序的入口。同时,配置文件也可以被嵌入到jar,通过使用java -jar命令时加上-cp参数指定相应的配置文件路径来实现读取配置文件Java -jar命令的优势在于可以在不额外安装任何其他工具或库的情况下,轻松地启动Java程序,并且保证程序的可移植性和独立性。它适用于各种应用场景,比如打包成可执行的jar包来共享给其他用户,通过Jenkins等CI/CD工具自动化部署和执行等。 需要注意的是,使用Java -jar命令启动Java程序时,程序内部的类路径可能会受到限制。因此,在使用Java -jar命令时,需要注意程序路径资源引用是否正确。此外,配置文件也需要按照一定的格式进行编写,以保证程序的正常启动和运行。 ### 回答2: Java -jar 配置文件是什么意思? Java -jar命令是用于启动Java应用程序的命令,而配置文件则是一种用于指定应用程序设置的文件。因此,Java -jar配置文件其实就是指定Java应用程序的配置文件,以便在运行Java应用程序时加载配置文件的设置。 Java应用程序的配置文件通常使用XML或属性文件格式,包含有关应用程序的各种设置,如数据库连接字符串、日志级别、缓存大小等。在Java应用程序,通常使用Java配置库来读取和解析配置文件。 如何使用Java -jar配置文件? 使用Java -jar配置文件的步骤如下: 1. 编写配置文件。创建一个XML或属性文件,设置应用程序需要的各种设置。 2. 修改启动脚本。在启动脚本添加-javaoption参数,并指定要加载的配置文件路径。例如: java -jar MyApp.jar -javaoption:-Dconfig.file=/path/to/config.xml 3. 在Java应用程序加载配置。使用Java配置库加载和解析配置文件,以获取应用程序需要的设置。 使用Java -jar配置文件的好处? 使用Java -jar配置文件的好处在于: 1. 管理应用程序设置。通过配置文件,可以方便地管理应用程序的各种设置,而不需要修改Java应用程序的代码。 2. 提高应用程序的灵活性。通过配置文件,可以动态地改变应用程序的设置,而无需重新编译和部署Java应用程序。 3. 便于维护和升级。通过配置文件,可以将应用程序的设置与代码分开,使维护和升级更加方便。 ### 回答3: Java -jar 配置文件是指通过命令行方式启动 Java 应用程序,并通过指定配置文件的方式进行应用程序的配置。一般来说,Java 应用程序需要在启动时加载各种配置信息,例如数据库连接信息、应用程序参数、系统参数等等,因此需要通过配置文件的方式来管理这些信息。 Java -jar 命令是 Java 运行环境提供的一个命令行工具,可以将一个以 jar 文件格式打包的 Java 应用程序直接在命令行运行。通过 -jar 参数指定要启动的 jar 文件名,就可以启动 Java 应用程序。 而在启动时,若需要加载配置文件,则可以通过在命令行指定配置文件路径,并由 Java 应用程序来加载、解析和使用配置文件的各项配置信息。例如,可以使用 -D 参数指定 Java 系统属性或使用 -cp 参数指定类路径等等。 当然,在实际使用,不同的 Java 应用程序会有不同的配置文件格式和加在方式,具体操作需要参考该应用程序的文档说明或开发者规范。但总体来说,利用 Java -jar 配置文件可以方便、快捷地启动并配置 Java 应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值