环球军事
properties(Java集合-Properties)

为了使用Properties类,则必须使用Properties的实例,可以通过构造函数创建:

Properties properties = new Properties();

设置Properties

设置了email为john@doe.com。

获取Properties

可以通过remove()方法移除指定的键值对,参数是key:

properties.remove("email");

迭代Properties

上面例子输出结果:

key1 = value1key2 = value2key3 = value3

存储Properties到文件

Properties文件的默认代码ISO-8859-1(Latin-1),然而我们常用的是 UTF-8编码,可以通过FileWriter构造函数的第二个参数指定具体的编码格式:

try(FileWriter output = new FileWriter("data/props.properties", Charset.forName("UTF-8"))){    properties.store(output, "These are properties");} catch (IOException e) {    e.printStackTrace();}

Property文件格式

#开头的是注释。

加载文件的数据到Properties

load()默认加载编码是ISO-8859-1 (Latin-1),如果需要使用其他格式,例如UTF-8,可以在使用 FileReader的第二个参数指定 UTF-8加载文件:

try(FileReader fileReader = new FileReader("data/props.properties", Charset.forName("UTF-8"))){    properties.load(fileReader);} catch (IOException e) {    e.printStackTrace();}

存储Properties中的数据到XML文件

Properties XML property 文件默认的编码UTF-8,如果需要使用其他编码格式则使用第三个参数例如ISO-8859-1:

try(FileOutputStream output = new FileOutputStream("data/props.xml")){    properties.storeToXML(output, "These are properties", Charset.forName("ISO-8859-1"));} catch (IOException e) {    e.printStackTrace();}

XML Property文件格式

请注意传递给storeToXML()方法的注释comment元素 是如何包含在注释XML元素中的,而不是包含在XML注释(<!-- -->) 。

从XML文件中加载到Properties

默认loadFromXML() 方法加载XML文件的编码格式是UTF-8 ,注意,这与非XML属性文件的默认值相反,如果XML文件使用不同的编码,例如ISO-8859-1(Latin-1),则XML文件必须指定其中的编码。这是通过将以下行作为XML属性文件的第一行来实现的:

<?xml version="1.0" encoding="ISO-8859-1"?>

从Classpath 路径下加载Properties

一旦有了Class实例可以通过 getResourceAsStream() 方法返回InputStream

InputStream inputStream =    aClass.getResourceAsStream("/myProperties.properties");

使用InputStream 把文件数据加载到Properties实例中,可以使用load() 或者loadFromXML()方法:

Class aClass = PropertiesExample.class; InputStream inputStream =    aClass.getResourceAsStream("/myProperties.properties"); Properties fromClasspath = new Properties(); try {    fromClasspath.load(inputStream);} catch (IOException e) {    e.printStackTrace();}

ResourceBundle Properties

Java Properties类能够为没有在Properties实例中注册任何键的属性提供默认属性值。有两种使用默认属性值的方法:

  • 为getProperty()方法提供默认的值
  • 创建Properties 实例时,提供包含默认值的Properties

getProperty()的默认值

如果 Properties实例中不包括key为preferredLanguage的实例,那么将返回Danish 。

使用默认的Properties实例作为默认值

在newProperties实例中我们没有设置preferredLanguage 的值,那么将取 defaultProperties中对应的preferredLanguage 的值。 f

系统Properties

可以通过 System.getProperty() 获取值和 System.setProperty() 设置值:

System.setProperty("key1", "value1");String value1 = System.getProperty("key1"); //The above is equal to: Properties systemProperties = System.getProperties(); systemProperties.setProperty("key1", "value1");String value1 = systemProperties.getProperty("key1");

通过系统命令设置System Properties

设置System property 名称key1和值 value1.

参考:http://tutorials.jenkov.com/java-collections/properties.html

https://blog.csdn.net/cgsyck/article/details/108449964


顶一下()     踩一下()

热门推荐

发表评论
0评