Springboot项目打jar包,无法读取资源文件

在设计项目时候,使用json文件来进行接口模板匹配使用。但是在使用开发过程中,用的好好的,并且能够进行配置文件读取,遍历文件夹,但是后期问题就出现了。在 要测试使用时候,打成jar包以后。就不能使用了。最后改变设计方式。直接通过InputStream来进行针对性解析文件。
这些方案还是通过网上资料查询汇总的。如果有谁有更好的方式麻烦留言。我想做到的是资源文件初始化就能够文件夹遍历循环读取资源文件,不需要针对性的开发模板才开始读取文件。

前提摘要:

为了能够读取resourse资源文件下自定义文件夹,则需要提前配置maven,否则默认仅加载读取resource下的文件,不能读取自定义文件夹中的文件。

资源文件结构目录 :

资源文件

maven特殊配置:
<build>

    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.json</include>
            </includes>
            <!--是否替换资源中的属性-->
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.json</include>
                <include>**/*.yml</include>
            </includes>
            <!--是否替换资源中的属性-->
            <filtering>false</filtering>
        </resource>
    </resources>
    </build>

这样就可以 读取资源 文件,自定义读取文件类型。
读取方式:

json:

   ClassPathResource classPathResource = new ClassPathResource(fileConnectPath);
   try{
    InputStream inputStream = classPathResource.getInputStream();
   	 StringBuilder builder = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader bfReader = new BufferedReader(reader);
        String tmpContent = null;
        while ((tmpContent = bfReader.readLine()) != null) {
            builder.append(tmpContent);
        }
      String jaon = builder.toString();//读取到文件字符串
      
		} catch (IOException e) {
            e.printStackTrace();
            log.error("The " + fileName + " file not exist in config/" + filePath + " path" + e);
        } finally {
         inputStream.close();
         bfReader.close();
        }

读取properties更方便:

Properties propertiesFile = new Properties();
 propertiesFile.load(inputStream); //inoutstream存放位置
 propertiesFile.getProperty(“配置文件中key值”);

然后可以本地打jar包读取尝试。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值