---
title: "Properties类小结"
author: "Rooock"
date: "2008-06-06T01:07:37Z"
tags: []
categories: ["企业架构"]
slug: "properties"
draft: false
lastmod: "2008-06-06T01:07:37Z"
id: 200729
url: "https://rooock.iteye.com/blog/200729"
---

目前有个任务,要用到java.util.Properties类及其拓展知识.在这里先把预备知识梳理一下,过几天再把commons configuration整理出来.

一.Properties 简介
	java.util.Properties 继承自 java.util.Hashtable 
	Properties 类表示一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串.

二.基本方法
2.1	如何从输入流中加载属性文件
	使用load(InputStream is)方法:

```java

Properties properties = new Properties();
InputStream is = new FileInputStream("conn.properties");
properties.load(is);
is.close();

```


2.2	如何读属性文件中的值
	使用getProperties(String key)方法:

```java

String temp = properties.getProperties(String key);

```


	<注>重载的方法getProperties(String key, String default)方法 将在查询不到值的情况下,返回default.
	即:	如果	 null		== properties.getProperties(String key);
		则有	 default	== properties.getProperties(String key, String default);

2.3	如何获取属性文件中的所有的键
	使用propertyNames()方法,该方法返回是键的枚举.

```java

Enumeration enumeration = properties.propertyNames();

```


2.4	如何修改属性文件中的值
	使用
```java
setProperties(String key, String value)
```
方法.
	<注>该方法调用的 Hashtable 的put方法.如果键存在,则修改值;如果键不存在,则添加值.

2.5	如何存储属性文件到输出流
	使用store(OutputStream os, String description)方法:

```java

Properties properties = new Properties();
OutputStream os = new FileOutputStream("test.properties");
String description = "store properties to test.properties";
properties.store(os, description);
os.close();

```


2.6	如何清空所有值
	使用
```java
clear()
```
方法.
	<注>该方法继承自 Hashtable 的clear()方法.清空哈希表.

三.实例附件
<注>实例中没有指明properties文件的绝对路径.那么默认是在项目根目录下的.
当生成新文件时,使用F5刷新就能看见新文件产生了.