Java Properties 类

Java 教程 · 2019-02-09 14:41:32

Properties 继承于 Hashtable.表示一个持久的属性集.属性列表中每个键及其对应值都是一个字符串。

Properties 类被许多Java类使用。例如,在获取环境变量时它就作为System.getProperties()方法的返回值。

Properties 定义如下实例变量.这个变量持有一个Properties对象相关的默认属性列表。

Properties defaults;

Properties类定义了两个构造方法. 第一个构造方法没有默认值。

Properties()

第二个构造方法使用propDefault 作为默认值。两种情况下,属性列表都为空:

Properties(Properties propDefault)

除了从Hashtable中所定义的方法,Properties定义了以下方法:

序号 方法描述
1 String getProperty(String key)
 用指定的键在此属性列表中搜索属性。
2 String getProperty(String key, String defaultProperty)
用指定的键在属性列表中搜索属性。
3 void list(PrintStream streamOut)
 将属性列表输出到指定的输出流。
4 void list(PrintWriter streamOut)
将属性列表输出到指定的输出流。
5 void load(InputStream streamIn) throws IOException
 从输入流中读取属性列表(键和元素对)。
6 Enumeration propertyNames( )
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
7 Object setProperty(String key, String value)
 调用 Hashtable 的方法 put。
8 void store(OutputStream streamOut, String description)
 以适合使用  load(InputStream)方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。

实例

下面的程序说明这个数据结构支持的几个方法:

实例

import java.util.*; public class PropDemo { public static void main(String args[]) { Properties capitals = new Properties(); Set states; String str; capitals.put("Illinois", "Springfield"); capitals.put("Missouri", "Jefferson City"); capitals.put("Washington", "Olympia"); capitals.put("California", "Sacramento"); capitals.put("Indiana", "Indianapolis"); // Show all states and capitals in hashtable. states = capitals.keySet(); // get set-view of keys Iterator itr = states.iterator(); while(itr.hasNext()) { str = (String) itr.next(); System.out.println("The capital of " + str + " is " + capitals.getProperty(str) + "."); } System.out.println(); // look for state not in list -- specify default str = capitals.getProperty("Florida", "Not Found"); System.out.println("The capital of Florida is " + str + "."); } }

以上实例编译运行结果如下:

The capital of Missouri is Jefferson City.
The capital of Illinois is Springfield.
The capital of Indiana is Indianapolis.
The capital of California is Sacramento.
The capital of Washington is Olympia.

The capital of Florida is Not Found.

点击查看所有 Java 教程 文章: https://codercto.com/courses/l/12.html

查看所有标签

人月神话

人月神话

[美] 弗雷德里克·布鲁克斯 / 汪颖 / 清华大学出版社 / 2002-11 / 29.80元

作者为人们管理复杂项目提供了颇具洞察力的见解,既有很多发人深省的观点,也有大量的软件工程实践。书中的内容来自布鲁克斯在IBM公司System 360家族和OS 360中的项目管理经验。初版的20年后,布鲁克斯重新审视了他原先的观点,增加了一些新的想法和建议。新增加的章节包括:原著中一些核心观点的精华;在经过了一个时代以后,Brooks博士对原先观点新的认识;1986年的经典文章《没有银弹》;对19......一起来看看 《人月神话》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换