Java中如何去读取resources.properties文件

package com.bonatone.knowledge.util;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class ResourcesUtil {
    
    public static String getProperties(String name){
        Properties props = getPropertiesInCache();
        String value = props.getProperty(name);
        return value;
    }
    
    public static Properties getPropertiesInCache() throws SecurityException {
        Properties pro = null;
        if(pro == null){
            pro = getProperties();
        }
        return pro;
    }
    
    private static Properties getProperties(){
        try {
            InputStream in = Thread.currentThread().getContextClassLoader().getResource("resources.properties").openStream();
            Properties props = new Properties();
            props.load(in);
            in.close(); // 别忘了关流
            return props;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    
    public static void putPropertiesToCache(){
        Properties pro = getProperties();
    }
}

最常用读取properties文件的方法
InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:
InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");
Java中获取路径方法
获取路径的一个简单实现

反射方式获取properties文件的三种方式

1 反射方式获取properties文件最常用方法以及思考:
Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但我见到众多读取properties文件的代码中,都会这么干:

InputStream in = getClass().getResourceAsStream("资源Name");

2 获取路径的方式:

File fileB = new File( this .getClass().getResource( "" ).getPath());
 
System. out .println( "fileB path: " + fileB);

3 利用反射的方式获取路径:

InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "xx/xx/xx/xx.properties" );
 
InputStream ips2 = Enumeration . class .getResourceAsStream( "xx.properties" );
 
InputStream ips3 = Enumeration . class .getResourceAsStream( "xx/xx.properties" );
---------------------
作者:西部落酋长
来源:CSDN
原文:https://blog.csdn.net/a913858/article/details/82769869
版权声明:本文为博主原创文章,转载请附上博文链接!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值