Java顺序读写Properties配置程序转载
原创1.Properties类与Properties配置文件
Properties类继承自Hashtable类和工具Map接口,它还使用键值对的形式来保存一组属性。但是Properties特别的是它的键和值是字符串类型。
2. Properties中的主要方法****
(1)load(InputStream inStream)
该方法可从.properties在与属性文件对应的文件输入流中,将属性列表加载到 Properties类对象 。 作为以下代码:
Properties pro = new Properties(); FileInputStream in = new FileInputStream("a.properties"); pro.load(in); in.close();
(2)store(OutputStream out, String comments)
此方法将 **Properties类对象的 保存到输出流的属性列表**** 。** 作为以下代码:
FileOutputStream oFile = new FileOutputStream(file, "a.properties"); pro.store(oFile, "Comment"); oFile.close();
如果comments不为空,保存的属性文件的第一行将为#comments,表示注释信息;如果为空,则无注释信息。
注释信息之后是属性文件的当前保存时间信息。
(3)getProperty/setProperty
这两种方法分别是获取和设置属性信息。
3.代码实例
属性文件a.properties如下:
name=root pass=liu key=value
读取a.properties属性列表,生成属性文件b.properties。代码如下:
1 import java.io.BufferedInputStream;
2 import java.io.FileInputStream;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.util.Iterator;
6 import java.util.Properties;
7
8 public class PropertyTest {
9 public static void main(String[] args) {
10 Properties prop = new Properties();
11 try{
12 //读取属性文件a.properties
13 InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));
14 prop.load(in); ///加载属性列表
15 Iterator
22 ///保存属性b.properties文件
23 FileOutputStream oFile = new FileOutputStream("b.properties", true);//true指示附加打开
24 prop.setProperty("phone", "10086");
25 prop.store(oFile, "The New properties file");
26 oFile.close();
27 }
28 catch(Exception e){
29 System.out.println(e);
30 }
31 }
32 }
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除