java resourcebundle_Java - Properties和ResourceBundle类学习

一、前言

在项目的开发过程中,为了统一配置的管理,我们经常需要将一些配置信息根据环境的不同,配置在不同的properties中,然后从里面进行读取。而Properties类作为最基础也是最经常使用的类,通过本文我们来学习一下它的使用,然后再顺便学习下其他几种读取properties文件的方式。

二、Properties和ResourceBundle类

Properties表示一个持久的属性集,属性列表通过key-value的形式存在,并且key和value都是字符串。我们先来看一下它的继承结构:

1. Properties 继承结构

public

class Properties extends Hashtable {

/**

* A property list that contains default values for any keys not

* found in this property list.

*

* @serial

*/

protected Properties defaults;

public Properties() {

this(null);

}

public Properties(Properties defaults) {

this.defaults = defaults;

}

}

看到它的继承结构,就知道这个类已经存在好久了。该类继承自Hashtable,所以该类拥有Map的一切功能,所以Map的put或者putAll方法都可以使用。

不过由于Properties中的每个key及value都是字符串,所以官方强烈反对使用它们,因为这些方法允许key或者value不是字符串,如果在set或get操作的时候,不是字符串的话,则会提示异常,所以建议使用的则是诸如setProperty这些方法。

2. Properties常用方法

这里Map相关的方法就不介绍了,主要介绍下自定义的方法:

2.1 setProperty方法

public synchronized Object setProperty(String key, String value) {

return put(key, value);

}

底层通过Hashtable的put方法来实现,该方法的目的就是强制对属性的key和value都使用字符串的形式;

2.2 getProperties方法

public String getProperty(String key)

public String getProperty(String key, String defaultValue) {

String val = getProperty(key);

return (val == null) ? defaultValue : val;

}

获取属性列表中属性的key对应的值,第二个重载方法表示如果获取不到值返回参数中提供的默认值。

2.3 load方法

public synchronized void load(Reader reader) throws IOException

public synchronized void load(InputStream inStream) throws IOException

load方法表示从输入流(字节流和字符流)中读取属性列表到Properties中,读取的时候按照行进行读取。而有关读取行及相关转义的说明,可以参考对应的API文档,上面有详细的说明。

2.4 loadFromXML方法

public synchronized void loadFromXML(InputStream in)

throws IOException, InvalidPropertiesFormatException

从输入流中读取XML文件中的所有属性,注意XML文档必须有相应的DTD声明:

2.5 store方法

public void store(Writer writer, String comments)

throws IOException

public void store(OutputStream out, String comments)

throws IOException

和load的功能相反,将Properties的属性列表写入到输出流,其中参数表示对属性列表的说明。

2.6 storeToXML方法

public void storeToXML(OutputStream os, String comment)

throws IOException

public void storeToXML(OutputStream os, String comment, String encoding)

throws IOException

将属性写入到xml,并可以指定的编码格式。

2.7 propertyNames和stringPropertyNames方法

public Enumeration> propertyNames()

public Set stringPropertyNames()

两个方法都是返回Properties属性列表中所有key,前者返回所有枚举,后者返回类型是字符串,注意如果没有在主属性列表中找到同名的键,则在默认属性列表中进行查找。

2.8 list方法

public void list(PrintStream out)

public void list(PrintWriter out)

将属性列表输出到指定的输出流,这个方法对调试很有用。

3. ResourceBundle简介

ResourceBundle没有继承什么类,是一个单个的抽象类,该类可以说是国际化版的Properties,简单说就是可以根据本地化或语言的不同读取不同的配置文件,但要注意的一点是使用ResourceBundle读取的时候,properties的命名是有一定规范的:

名称_语言代码_国家代码.properties

// 如果是默认的

自定义名.properties

// 例如

myres_en_US.properties

myres_zh_CN.properties

myres.properties

当指定的Locale是CN的时候,如果myres_zh_CN.properties、myres.properties两个文件都存在,则优先会使用myres_zh_CN.properties,当myres_zh_CN.properties不存在时候,会使用默认的myres.properties。

4. ResourceBundle常用方法

4.1 getBundle方法

ResourceBundle提供了多个重载的静态getBundle方法,用于获取资源文件,这里我们不多介绍,后续看实例即可:

public static final ResourceBundle getBundle(String baseName)

public static final ResourceBundle getBundle(String baseName,

Locale locale)

public static ResourceBundle getBundle(String baseName, Locale locale,

ClassLoader loader)

public static final ResourceBundle getBundle(String baseName,

Control control)

public static ResourceBundle getBundle(String baseName, Locale targetLocale,

ClassLoader loader, Control control)

4.2 getObject,getString,getStringArray方法

getString方法比较简单,就是根据key获取属性列表中key对应的value,key和value都是String;

getStringArray方法,用于获取字符串数组,返回值是字符串数组;

getObject方法,通用的获取方法,获取其他任何类型;

public final String getString(String key)

public final String[] getStringArray(String key)

public final Object getObject(String key)

4.3 keySet,getKeys,containsKey方法

这几个方法都比较简单,见名知义,其中getKeys表示返回key的枚举形式。

public Set keySet()

public abstract Enumeration getKeys();

public boolean containsKey(String key)

4.4 getBaseBundleName,getLocale方法

getBaseBundleName方法就是获取加载的资源文件的文件名的,getLocale获取本地化环境信息的。

public String getBaseBundleName()

public Locale getLocale()

4.5 clearCache方法

通过getBundle方法读取资源文件,获取ResourceBundle时是从缓存中获取的,如果已经缓存,工厂方法将多次返回相同的资源实例,而clearCache方法就是用于清除缓存的:

public static final void clearCache()

public static final void clearCache(ClassLoader loader)

4. 简单示例

接下来我们来简单看下这些方法的相关使用说明。

4.1 Properties 通过store方法写入对应的文件中

首先我们调用setProperty方法会将key-value存于内存中,此时可以通过getProperty方法读取,propertyNames方法进行遍历,但是并没有将键值对持久化到属性文件中,故需要调用store方法持久化键值对到属性文件中。

Properties properties = new Properties();

try {

OutputStream output = new FileOutputStream("cache.properties");

properties.setProperty("redis.server.address", "127.0.0.1");

properties.setProperty("redis.server.port", "6379");

properties.setProperty("redis.server.password", "");

properties.setProperty("redis.server.timeout", "2000");

properties.store(output, "缓存文件配置测试");

} catch (IOException io) {

io.printStackTrace();

} finally {

...

}

最终生成的cache.properties文件:

#缓存文件配置测试

#Sun Aug 19 12:27:05 CST 2018

redis.server.timeout=2000

redis.server.address=127.0.0.1

redis.server.password=

redis.server.port=6379

4.2 Properties使用load方法加载

同样,我们可以通过load方法将属性文件中的属性加载到Properties对象中,然后进行访问:

Properties properties = new Properties();

InputStream inputStream = null;

try {

inputStream = new FileInputStream("cache.properties");

properties.load(inputStream);

for (String key : properties.stringPropertyNames()) {

System.out.println(key + "=" + properties.getProperty(key));

}

} catch (IOException io) {

io.printStackTrace();

} finally {

...

}

最终结果:

redis.server.timeout=2000

redis.server.address=127.0.0.1

redis.server.password=

redis.server.port=6379

因为Properties其实是一个Map,所以Map的遍历方式也适用于Properties,也可也借助Properties的propertyNames方法来进行遍历:

Enumeration> e = properties.propertyNames();

while (e.hasMoreElements()) {

String key = (String) e.nextElement();

String value = properties.getProperty(key);

System.out.println(key + "=" + value);

}

4.3 ResourceBundle简单实例

我们先定义三个资源文件,放到src的根目录下面:

myres.properties

aaa=good

bbb=thanks

myres_en_US.properties

aaa=good

bbb=thanks

myres_zh_CN.properties

aaa=好

bbb=谢谢

添加测试代码:

public static void main(String[] args) {

Locale locale1 = new Locale("zh", "CN");

ResourceBundle resb1 = ResourceBundle.getBundle("cache", locale1);

System.out.println(resb1.getString("aaa"));

ResourceBundle resb2 = ResourceBundle.getBundle("cache", Locale.getDefault());

System.out.println(resb1.getString("aaa"));

Locale locale3 = new Locale("en", "US");

ResourceBundle resb3 = ResourceBundle.getBundle("cache", locale3);

System.out.println(resb3.getString("aaa"));

}

output:

good

这里需要注意下,通过getBundle方法来获取的时候,参数不用加properties后缀,只需要文件名就可以了,并且默认访问的路径是src,如果文件保存在其他目录,记得修改到对应的目录。

5. 其他读取properties文件的方法

5.1 Properties其他获取InputStream的方法

在这里,其实读取properties都是通过Properties来实现的,不过不同的是获取InputStream流的方式,我们来看一下各种获取InputStream流的方式:

从File文件获取:

InputStream inputStream = new FileInputStream(new File ("cache.properties"));

根据ClassLoader的getResourceAsStream方法来获取。其中该方法又分为两种方式:

Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取。其实只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源;

Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源;

ServletContext.getResourceAsStream(String path):默认从WebAPP根目录下取资源,Tomcat下path是否以’/'开头无所谓,当然这和具体的容器实现有关;

InputStream inputStream = PropertiesTest.class.getResourceAsStream("cache.properties");

通过URL来获取:

URL url = new URL("path");

InputStream inputStream= url.openStream();

如果是Spring环境,还可以通过ResourceLoader的getResource得到Resource,然后通过Resource的getInputStream来得到流:

ResourceLoader resourceLoader = new DefaultResourceLoader();

Resource resource = resourceLoader.getResource("/config/cache.properties");

inputStream = resource.getInputStream();

5.2 ResourceBundle类相关方法

前面也已经简单介绍过,我们可以借助java.util.ResourceBundle的getBundle静态方法来获取资源实例:

Locale locale1 = new Locale("zh", "CN");

ResourceBundle resb1 = ResourceBundle.getBundle("cache", locale1);

另外,也可以借助实现类 PropertyResourceBundle 通过从输入流中进行读取:

inputStream = new FileInputStream("cache.properties");

ResourceBundle resource = new PropertyResourceBundle(inputStream);

不过如果有兴趣的话可以看下PropertyResourceBundle的构造方法,它其实是借助Properties和HashMap来实现的:

public PropertyResourceBundle (InputStream stream) throws IOException {

Properties properties = new Properties();

properties.load(stream);

lookup = new HashMap(properties);

}

private Map lookup;

三、总结

到这里,就基本介绍完了Properties和ResourceBundle类及如何读取properties文件,其实,介绍的都比较基础,需要注意的可能就两点吧:一是路径的问题,二是流的关闭和异常处理问题。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/268765.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java中Collections.singletonList用法

Collections.singletonList()返回的是不可变的集合,但是这个长度的集合只有1,可以减少内存空间。但是返回的值依然是Collections的内部实现类,同样没有add的方法,调用add,set方法会报错 调用add方法报错 Exception in…

最近找工作的面试经历

来到广州已经一个星期了&#xff0c;招聘会参加了两场&#xff0c;面试了三间公司&#xff0c;但都是通知回去等结果。回想一下这几天的面试经历&#xff0c;感觉自己要学的东西还很多。 <?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office&quo…

CF Round410 D. Mike and distribution

D. Mike and distribution 构造法 798D - Mike and distribution In the beginning, its quite easy to notice that the condition " 2(ap1  ...  apk) is greater than the sum of all elements in A " is equivalent to " ap1  ...  apk is greater …

OOAD实践之路——真实案例解析OO理论与实践(二、第一项任务:特性列表)

查看本系列全部文章&#xff1a;《OOA&D实践之路——真实案例解析OO理论与实践》索引贴 第一份说明 当这个项目开始时&#xff0c;我们得到的关于我们要做的系统的唯一说明是一页Word文档&#xff0c;这是一份简单的不能再简单的说明。文档里只有一行字&#xff1a;我…

CSS3常用属性及用法

1.transition: 过渡属性&#xff0c;可以替代flash和javascript的效果 兼容性&#xff1a;Internet Explorer 9 以及更早的版本&#xff0c;不支持 transition 属性。 Chrome 25 以及更早的版本&#xff0c;需要前缀 -webkit-。 Safari 需要前缀 -webkit-。 div { transition: …

ADSL提速 从入门到精通

虽然现在的宽带速率已经很快了&#xff0c;但是大家还是希望在以下方面提升一下应用速度&#xff1a;电影BT下载时、在线影音播放时、FTP文件传送时等。广大网友也因此探寻出不少提升宽带速率的方法&#xff0c;那么&#xff0c;都有哪些简单可行的提速方法呢&#xff1f;它们的…

Swift开发图解入门

《论语卫灵公》有一段经典对白&#xff1a;『子贡问为仁。子曰&#xff1a;工欲善其事&#xff0c;必先利其器。……』。对于一个程序猿来说&#xff0c;好的工具不意味着一定能产生优质的代码。可是好的工具对提升开发效率的作用还是不言而喻的。想要用Swift做iOS开发。唯一可…

java 负数存储结构_负数在java中的存储和读取过程 | 学步园

问题描述&#xff1a;将-5存储在文本文件中&#xff0c;再读取出来显示到控制台;预备知识&#xff1a;1.在java中使用补码处理数字&#xff0c;而且byte(8)的数字在扩展成int(32)类型的时候&#xff0c;正数填充0&#xff0c;负数填充1;2.负数的转变过程&#xff0c;正数的原码…

爆笑:可怜的话剧演员

地点&#xff1a;中央戏剧学院的话剧排练场。   事件&#xff1a;一场文艺剧目的排练。   人物&#xff1a;一男一女。   女&#xff08;羞涩的&#xff09;&#xff1a;我看啊&#xff0c;咱俩的婚事儿&#xff0c;都是你妈逼的。   男&#xff08;憨笑著&#xff0…

获取文本中你须要的字段的 几个命令 grep awk cut tr sed

1,grep 2,awk 3,cut 4,tr 5,sed 实例1 获取本地IP地址 /sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6 | awk {print $2} | tr -d "addr:" 实例2 sed 的使用。去掉某字段 前后的值 grep "select" slow.log | grep "from" | s…

一升的眼泪 日记原文+剧照

作者 木藤亚也14岁——我的家人  “我不能活动&#xff0c;可是我想活着……”   然而&#xff0c;我怎么也想不到&#xff0c;就在我生日这一天&#xff0c;却发生了一场悲剧——玛丽被邻居家养的大狗“老虎”咬破头&#xff0c;死了。玛丽虽然身体小小的&#x…

[补档]暑假集训D5总结

%dalao 今天又有dalao来讲课&#xff0c;讲的是网络流网络流——从入门到放弃&#xff1a;7-29dalao讲课笔记——https://hzoi-mafia.github.io/2017/07/29/27/果然是从入门到放弃啊&#xff0c;dalao本来说好下午继续讲完的&#xff0c;然后——就没有然后了重要的是&#xff…

在多线程中使用UDP

在多线程中使用UDP来自&#xff1a;painboy, 时间&#xff1a;2004-8-8 11:34:40, ID&#xff1a;2754268 type TUdpThread class(TThread) private FData : PChar; //数据区 FBytes : Integer; //数据区大小 FFromIP : string; //UDP的…

主流浏览器Cssjs hack写法

参考&#xff1a; BROWSER HACKS 主流浏览器的Hack写法 转载于:https://www.cnblogs.com/huangtailang/p/7279634.html

java管道流文件的复制_JavaIO 总结笔记三 基本字节字符输入输出流和文件复制...

一、IO体系1.流主要分两大类&#xff1a;字节流 字符流2.在硬盘上的文件&#xff0c;都是以二进制字节形式存储的&#xff0c;所以不管啥文件&#xff0c;读写时都应该用字节流3.在java的早期版本中&#xff0c;的确只有字节流&#xff0c;没有字符流4.一个数字或字母占1个字节…

mysql+phpmyadmin配置流程

mysqlphpmyadmin配置流程&#xff1a;环境&#xff1a;Apachephp5mysql5下载包&#xff1a;phpMyAdmin-2.11.9.4-all-languages-utf-8-only.tar.gz不能下就到这里下载 [url]http://www.phpmyadmin.net/home_page/downloads.php[/url]一&#xff1a;安装配置1> 安装包&#x…

hadoop入门小知识点

注意各个主机之间的通信 文件的复制 scp指令 scp /etc/profile acm03:/etc 所有历史版本&#xff1a; archive.apache.org hdfs://acm01:9000 hdfs是个协议 然后 访问谁 哪个端口 统一资源定位符URL 客户端统统 找nameinode 访问它 启动 datanode hadoop-dae…