Properties

一.定义

Properties类继承自Hashtable(Hashtable实现了Map接口),它表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

常用方法:

void     load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。

String  getProperty(String key) 在属性列表中根据key获取value。

Object  setProperty(String key,String Value)调用 Hashtable 的put方法,给属性列表增加属性,但不修改properties配置文件 

void     store(OutputStream out,String comments)将属性列表(键和元素对)写入输出流(即写到properties属性文件中)。

二.测试

1.新建一个普通java项目,在根目录下创建文件test.properties(.properties文件默认使用ISO-8859-1编码,不能显示中文,可自行设置)
test1=\u6D4B\u8BD51
test2=test2
test8=ttt

其中test1的值为"测试1"

2.src下创建测试类
 1 package test;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.util.Properties;
 8 
 9 /**
10  * 运用Properties对象读写properties属性文件
11  * @author phase1
12  *
13  */
14 public class TestProperties {
15     public static void main(String[] args) {
16         //创建Properties对象
17         Properties prop = new Properties();
18         //创建输入流,指向配置文件
19         FileInputStream fis = null;
20         //创建输出流,指向新的文件;也可以指向原文件
21         FileOutputStream fos = null;
22         try {
23              fis= new FileInputStream("test.properties");
24              fos= new FileOutputStream("copy.properties");
25              //加载属性文件
26              prop.load(fis);
27              //读取配置文件的键值
28              System.out.println(prop.getProperty("test1"));
29              //设置新属性,(但不修改属性文件)
30              prop.setProperty("test3", "---");
31              //创建新的(或修改原文件),第二个参数为新文件的说明性字符串,放在属性文件的第一行
32              prop.store(fos,"new properties");
33         } catch (FileNotFoundException e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36         } catch (IOException e){
37             e.printStackTrace();
38         } finally{
39             if(fis!=null){
40                 try {
41                     fis.close();
42                     fos.close();
43                 } catch (IOException e) {
44                     // TODO Auto-generated catch block
45                     e.printStackTrace();
46                 }
47             }
48         }
49     }
50 }
3.运行测试类,刷新项目,项目根目录下会多出一个新的文件copy.properties
1 #new properties
2 #Thu Oct 27 11:28:43 CST 2016
3 test3=---
4 test2=test2
5 test1=\u6D4B\u8BD51
6 test8=ttt

同时控制台会输出:测试1

 

posted @ 2016-10-27 11:53  执迷而不悔  阅读(389)  评论(0编辑  收藏  举报