Java 读写Properties配置文件

1.Properties类与Properties配置文件

什么是java的配置文件?  在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。

2.Properties中的主要方法

1. getProperty / setProperty

   这两个方法是分别是获取和设置属性信息。

2. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

3. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

4. store ( OutputStream out, String comments),将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

3. 编写读取.properties的两种方式

//方式一:
		File file = new File("aa.properties");
		Properties pro = new Properties();
		pro.setProperty("1", "张三");
		pro.setProperty("2", "李四");
		pro.store(new PrintStream(file), "utf-8");
		pro.load(new FileInputStream(file));
		
		System.out.println(pro.getProperty("1"));
		System.out.println(pro.getProperty("2"));

   

//方式二:
		File fi = new File("fil.properties");
		Properties pro  = new Properties();
		pro.put("1", "你的");
		pro.put("2", "真的");
		pro.store(new PrintStream(fi), "UTF-8");
		pro.load(new FileInputStream(fi));
		
		System.out.println(pro.get("1"));
		System.out.println(pro.get("2"));

 

原文地址:https://www.cnblogs.com/gshao/p/10217574.html