“今天我们要探索另一个有趣的新话题:属性。

“在 Java 中,通常使程序灵活且易于定制,即易于配置。”

“例如,您的程序每小时从某个目录复制文件一次,压缩它们,然后通过电子邮件将它们发送给您。为此,程序需要知道文件将从中获取的目录以及电子邮件地址它们应该发送到哪里。此类数据通常不存储在应用程序代码中,而是存储在单独的属性文件中。

此文件中的数据存储为键值对,由等号分隔。

例子
data.properties file
directory = c:/text/downloads
email = zapp@codegym.cc

“符号的左边是名称(键),右边是值。”

“所以这是 HashMap 的一种文本表示?”

“一般来说,是的。”

“为了方便处理此类文件,Java 有一个特殊的 Properties 类。Properties 类继承了 Hashtable<Object,Object>。它甚至可以被认为是一个可以从文件加载自身的 Hashtable。”

“这是它的方法:”

方法 描述
void load(Reader reader) 从 Reader 对象表示的文件中加载属性
void load(InputStream inStream) 从 InputStream 对象表示的文件中加载属性
void loadFromXML(InputStream in) 从 XML 文件加载属性
Object get(Object key) 返回指定键的值。该方法继承自Hashtable
String getProperty(String key) 按键返回属性值(字符串)。
String getProperty(String key, String defaultValue) 如果没有这样的键,则按键或 defaultValue 返回属性值。
Set<String> stringPropertyNames() 返回所有键的列表

“换句话说,你实际上只需要执行两个操作——将数据从某个文件加载到Properties对象中,然后使用getProperty () 方法获取这些属性。好吧,不要忘记你可以像这样使用Properties对象一个哈希表。”

“这是另一个例子:”

代码
// The file that stores our project's properties
File file = new File("c:/data.properties");

// Create a Properties object and load data from the file into it.
Properties properties = new Properties();
properties.load(new FileReader(file));

// Get property values from the Properties object
String email = properties.getProperty("email");
String directory = properties.getProperty("directory");

// Get a numeric value from the Properties object
int maxFileSize = Integer.parseInt(properties.getProperty("max.size", "10000"));

“啊。所以我们创建一个 Properties 对象,然后将一个文件传递给它。传递给 load 方法。然后我们只调用 getProperty。对吗?”

“是的。”

“而且你还说可以当HashMap使用?什么意思?”

“Properties类继承了Hashtable,它和HashMap是一样的,但是它的所有方法都是同步的。你可以像这样简单地将属性文件中的所有值显示在屏幕上:”

代码
// Get the file with the properties
File file = new File("c:/data.properties");

// Create a Properties object and load data from the file into it.
Properties properties = new Properties();
properties.load(new FileReader(file));

// Run through all the keys and display their values on the console
for (String key : properties.stringPropertyNames())
{
 System.out.println(properties.get(key));
}

“啊。一切似乎都已经到位了。谢谢你,Rishi。我要用这个很酷的东西。”