JAVA加载properties配置文件

 

获得配置文件内容,其最大的问题就是文件路径的定位:

通过ClassLoader去加载资源。参数需要从classpath的入口来算起。也就是说需要取全路径名称。

    String  path =   当前类名.class.getClassLoader().getResource("").toURI().getPath() ;  //默认的是到src文件夹下

     或者

     String  path =   当前类名.getClassLoader().getResourceAsStream("conf/key-conf.properties"); //src文件夹下的conf/key-conf.properties

 

1、使用java.util.Properties类的load()方法 

 

InputStream in = lnew BufferedInputStream(new FileInputStream(name));   
Properties p = new Properties();   
p.load(in);  
View Code

 

2、使用java.util.ResourceBundle类的getBundle()方法  

 ResourceBundle这个类提供软件国际化的捷径 。使用这个类,要注意的一点是,这个properties文件的名字是有规范的:

一般的命名规范是: 自定义名_语言代码_国别代码.properties, 

如果是默认的,直接写为: 自定义名.properties
比如:
myres_en_US.properties
myres_zh_CN.properties
myres.properties
当在中文操作系统下,如果myres_zh_CN.properties、myres.properties两个文件都存在,则优先会使用myres_zh_CN.properties,当myres_zh_CN.properties不存在时候,会使用默认的myres.properties。

定义资源文件,放到src的根目录下面:(注意不在src的根目录下,路径分割符用的是 " . ")

myres.properties
aaa=good 
bbb=thanks

myres_en_US.properties
aaa=good 
bbb=thanks

myres_zh_CN.properties
aaa=\u597d 
bbb=\u591a\u8c22
                Locale locale1 = new Locale("zh", "CN"); 
                ResourceBundle resb1 = ResourceBundle.getBundle("myres", locale1); 
                System.out.println(resb1.getString("aaa")); 

                ResourceBundle resb2 = ResourceBundle.getBundle("myres", Locale.getDefault()); 
                System.out.println(resb1.getString("aaa")); 

                Locale locale3 = new Locale("en", "US"); 
                ResourceBundle resb3 = ResourceBundle.getBundle("myres", locale3); 
                System.out.println(resb3.getString("aaa")); 

 

 

 

 

 

转载于:https://www.cnblogs.com/pipi-582/p/3623657.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值