Getting Started with Java Properties – Java属性入门

最后修改: 2016年 11月 16日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Most Java application need to use properties at some point, generally to store simple parameters as key-value pairs, outside of compiled code.

大多数Java应用程序在某些时候需要使用属性,一般是在编译的代码之外将简单的参数存储为键值对。

And so the language has first class support for properties – the java.util.Properties – a utility class designed for handling this type of configuration files.

因此,该语言对属性有一流的支持–java.util.Properties–一个为处理这种类型的配置文件而设计的实用类。

That’s what we’ll focus on in this article.

这就是我们在本文中要关注的内容。

2. Loading Properties

2.加载属性

2.1. From Properties Files

2.1.来自属性文件

Let’s start with an example for loading key-value pairs from properties files; we’re loading two files we have available on our classpath:

让我们从一个从属性文件加载键值对的例子开始;我们正在加载我们在classpath上可用的两个文件。

app.properties:

app.properties:

version=1.0
name=TestApp
date=2016-11-12

And catalog:

还有目录

c1=files
c2=images
c3=videos

Notice that although the properties files are recommended to use “.properties“, the suffix, it’s not necessary.

请注意,尽管属性文件被推荐使用”.properties“这个后缀,但这不是必须的。

We can now load them very simply into a Properties instance:

现在我们可以非常简单地将它们加载到一个Properties实例中。

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String appConfigPath = rootPath + "app.properties";
String catalogConfigPath = rootPath + "catalog";

Properties appProps = new Properties();
appProps.load(new FileInputStream(appConfigPath));

Properties catalogProps = new Properties();
catalogProps.load(new FileInputStream(catalogConfigPath));

  
String appVersion = appProps.getProperty("version");
assertEquals("1.0", appVersion);
        
assertEquals("files", catalogProps.getProperty("c1"));

As long as a file’s content meet properties file format requirements, it can be parsed correctly by Properties class. Here are more details for Property file format.

只要一个文件的内容符合属性文件格式的要求,它就可以被属性类正确解析。这里有更多关于属性文件格式的细节。

2.2. Load From XML Files

2.2.从XML文件加载

Besides properties files, Properties class can also load XML files which conform to the specific DTD specifications.

除了属性文件,Properties类还可以加载符合特定DTD规范的XML文件。

Here is an example for loading key-value pairs from an XML file – icons.xml:

下面是一个从XML文件加载键值对的例子–icons.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>xml example</comment>
    <entry key="fileIcon">icon1.jpg</entry>
    <entry key="imageIcon">icon2.jpg</entry>
    <entry key="videoIcon">icon3.jpg</entry>
</properties>

Now, let’s load it:

现在,我们来加载它。

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String iconConfigPath = rootPath + "icons.xml";
Properties iconProps = new Properties();
iconProps.loadFromXML(new FileInputStream(iconConfigPath));

assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));

3. Get Properties

3.获取属性

We can use getProperty(String key) and getProperty(String key, String defaultValue) to get value by its key.

我们可以使用getProperty(String key)getProperty(String key, String defaultValue)来通过它的键获得值。

If the key-value pair exists, the two methods will both return the corresponding value. But if there is no such key-value pair, the former will return null, and the latter will return defaultValue instead.

如果键值对存在,这两个方法都将返回相应的值。但如果没有这样的键值对,前者将返回null,而后者将返回defaultValue

Example code:

示例代码。

String appVersion = appProps.getProperty("version");
String appName = appProps.getProperty("name", "defaultName");
String appGroup = appProps.getProperty("group", "baeldung");
String appDownloadAddr = appProps.getProperty("downloadAddr");

assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("baeldung", appGroup);
assertNull(appDownloadAddr);

Note that although Properties class inherits get() method from Hashtable class, I wouldn’t recommend you use it to get value. Because its get() method will return an Object value which can only be cast to String and the getProperty() method already handles the raw Object value properly for you.

注意,尽管Properties类从Hashtable类继承了get()方法,我不建议你用它来获取值。因为它的get()方法将返回一个Object值,而这个值只能被转换为String,并且getProperty()方法已经为你正确处理了原始Object值。

The code below will throw an Exception:

下面的代码将抛出一个Exception

float appVerFloat = (float) appProps.get("version");

4. Set Properties

4.设置属性

We can use setProperty() method to update an existed key-value pair or add a new key-value pair.

我们可以使用setProperty()方法来更新一个已经存在的键值对或添加一个新的键值对。

Example code:

示例代码。

appProps.setProperty("name", "NewAppName"); // update an old value
appProps.setProperty("downloadAddr", "www.baeldung.com/downloads"); // add new key-value pair

String newAppName = appProps.getProperty("name");
assertEquals("NewAppName", newAppName);
        
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);

Note that although Properties class inherits put() method and putAll() method from Hashtable class, I wouldn’t recommend you use them for the same reason as for get() method: only String values can be used in Properties.

注意,尽管Properties类从Hashtable类继承了put()方法和putAll()方法,我不建议你使用它们,原因与get()方法相同:只有String值可以用于Properties

The code below will not work as you wish, when you use getProperty() to get its value, it will return null:

下面的代码不会如你所愿,当你使用getProperty()来获取其值时,它将返回null

appProps.put("version", 2);

5. Remove Properties

5.删除属性

If you want to remove a key-value pair, you can use remove() method.

如果你想删除一个键值对,你可以使用remove()方法。

Example Code:

示例代码。

String versionBeforeRemoval = appProps.getProperty("version");
assertEquals("1.0", versionBeforeRemoval);

appProps.remove("version");    
String versionAfterRemoval = appProps.getProperty("version");
assertNull(versionAfterRemoval);

6. Store

6.商店

6.1. Store to Properties Files

6.1.存储到属性文件

Properties class provides a store() method to output key-value pairs.

Properties类提供了一个store()方法来输出键值对。

Example code:

示例代码。

String newAppConfigPropertiesFile = rootPath + "newApp.properties";
appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");

The second parameter is for comment. If you don’t want to write any comment, simply use null for it.

第二个参数是用于注释。如果你不想写任何评论,只需使用null。

6.2. Store to XML Files

6.2.存储到XML文件

Properties class also provides a storeToXML() method to output key-value pairs in XML format.

Properties类还提供了一个storeToXML()方法来输出XML格式的键值对。

Example code:

示例代码。

String newAppConfigXmlFile = rootPath + "newApp.xml";
appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");

The second parameter is as same as it in the store() method.

第二个参数与store()方法中的参数相同。

7. Other Common Operations

7.其他普通操作

Properties class also provides some other methods to operate the properties.

Properties类还提供了一些其他的方法来操作属性。

Example code:

示例代码。

appProps.list(System.out); // list all key-value pairs

Enumeration<Object> valueEnumeration = appProps.elements();
while (valueEnumeration.hasMoreElements()) {
    System.out.println(valueEnumeration.nextElement());
}

Enumeration<Object> keyEnumeration = appProps.keys();
while (keyEnumeration.hasMoreElements()) {
    System.out.println(keyEnumeration.nextElement());
}

int size = appProps.size();
assertEquals(3, size);

8. Default Property List

8.默认属性列表

A Properties object can contain another Properties object as its default property list. The default property list will be searched if the property key is not found in the original one.

一个Properties对象可以包含另一个Properties对象作为其默认属性列表。如果在原属性列表中找不到属性键,将搜索默认属性列表。

Besides “app.properties“, we have another file – “default.properties” – on our classpath:

除了”app.properties“,我们还有另一个文件–“default.properties” –在我们的classpath上。

default.properties:

default.properties。

site=www.google.com
name=DefaultAppName
topic=Properties
category=core-java

Example Code:

示例代码。

String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

String defaultConfigPath = rootPath + "default.properties";
Properties defaultProps = new Properties();
defaultProps.load(new FileInputStream(defaultConfigPath));

String appConfigPath = rootPath + "app.properties";
Properties appProps = new Properties(defaultProps);
appProps.load(new FileInputStream(appConfigPath));

assertEquals("1.0", appVersion);
assertEquals("TestApp", appName);
assertEquals("www.google.com", defaultSite);

9. Properties and Encoding

9.属性和编码

By default, properties files are expected to be ISO-8859-1 (Latin-1) encoded, so properties with characters outside of the ISO-8859-1 shouldn’t generally be used.

默认情况下,属性文件应该是ISO-8859-1(Latin-1)编码的,所以带有ISO-8859-1以外字符的属性一般不应该被使用。

We can work around that limitation with the help of tools such as the JDK native2ascii tool or explicit encodings on files, if necessary.

我们可以在JDK native2ascii工具等工具的帮助下绕过这一限制,或者在必要时对文件进行明确编码。

For XML files, the loadFromXML() method and the storeToXML() method use UTF-8 character encoding by default.

对于XML文件,loadFromXML()方法和storeToXML()方法默认使用UTF-8字符编码。

However, when reading an XML file encoded differently, we can specify that in the DOCTYPE declaration; writing is also flexible enough – we can specify the encoding in a third parameter of the storeToXML() API.

然而,当读取一个以不同方式编码的XML文件时,我们可以在DOCTYPE声明中指定;写作也足够灵活–我们可以在storeToXML() API的第三个参数中指定编码。

10. Conclusion

10.结语

In this article, we have discussed basic Properties class usage, including how to use Properties load and store key-value pairs in both properties and XML format, how to operate key-value pairs in a Properties object, such as retrieve values, update values, get its size, and how to use a default list for a Properties object.

在这篇文章中,我们讨论了基本的Properties类用法,包括如何使用Properties加载和存储属性和XML格式的键值对,如何在Properties对象中操作键值对,如检索值、更新值、获取其大小,以及如何为Properties对象使用默认列表。

The complete source code for the example is available in this GitHub project.

该示例的完整源代码可在此GitHub项目中获得。