java resource jar_jar包中如何读取项目中Resource下的文件

今天遇到一个巨大的坑就是一个简单的读取项目中的一个config.json文件。在本地是正常的,但是打包成jar包在linux上运行的时候死活找不到。

下面是我的项目结构

97cdf3986fa4

JIGOU.png

就是为了读取配置文件config.json的内容

刚开始是通过文件路径然后通过readFile("文件路径")的方式读取,但是使用过

this.getClass().getResource("/").getPath()+"config.json" //本地是可以的,但是打包成jar包之后再服务器中打印出的路径是一串数字。

String configPath = ResourceUtils.getFile("classpath:config.json").getAbsolutePath(); //也是不行

后面再网上找了使用getResourceAsStream() 方法搞定,代码如下

InputStream is = this.getClass().getResourceAsStream("/config.json");

BufferedReader br = new BufferedReader(new InputStreamReader(is));

String s="";

String configContentStr = "";

try {

while((s=br.readLine())!=null) {

configContentStr = configContentStr+s;

}

} catch (IOException e) {

e.printStackTrace();

}

顺便记录一下java中获取路径的一些方法

//获取类路径

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();

//因为程序已经被打包成jar包,所以getPath()和getFile()在这里的返回值是一样的。都是/xxx/xxx.jar这种形式。如果路径包含Unicode字符,还需要将路径转码

path = java.net.URLDecoder.decode(path, "UTF-8");

//利用了java运行时的系统属性来得到jar文件位置,也是/xxx/xxx.jar这种形式。

String path = System.getProperty("java.class.path");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值