java.util.Properties extends Hashtable<Object,Object> implements Map<key,value>
Properties类表示一个持久的属性集。Properties可以保存在流中或从流中加载
Properties集合是一个唯一和IO流相结合的集合
可以使用Properties集合中的store方法,将集合中的临时数据,持久化写入硬盘中存储
可以使用Properties集合中的load方法,把硬盘上的文件(文件里面存储着键值对),读取到内存集合中使用
属性列表每个键及其对应值都是一个字符串
Properties集合是一个双列集合,key和value默认都是字符串
使用Properties集合存储数据,遍历取出Properties集合中的数据
Properties集合是一个双列集合,key和value默认都是字符串
Properties集合有一些操作字符串的特有方法
setProperty(String key, String value)设置key和value--调用Hashtable的方法put
getProperty(String key)---通过key,找value----相当于Map集合中的get方法
Set<String> stringPropertyNames()---返回属性列表中的键集,该键对应的值为字符串,相当于Map集合中的keySet方法
package iotest.testProperties; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.Set; //Properties中字符串特有的操作方法,但不能保证Properties集合中的顺序 public class TestProperties01 { public static void main(String[] args) throws IOException { Properties properties = new Properties(); properties.setProperty("a","a1"); properties.setProperty("b","b1"); properties.setProperty("c","c1"); Set<String> set = properties.stringPropertyNames(); for (String key : set) { System.out.println(key+"-->"+properties.getProperty(key)); } } }
store方法:可以使用Properties集合中的store方法,将集合中的临时数据,持久化写入硬盘中存储
public void store(OutputStream out, String comments)
public void store(Writer writer, String comments)
comments:注释,用来解释保存的文件是干什么用的
不能用中文,会产生乱码,默认是Unicode编码,系统为GBK
一般使用“”空字符串
使用步骤
1.创建Properties集合对象,添加数据
2.创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
3.使用Properties集合中store方法,将集合中的临时数据,持久化写入硬盘
4.释放资源
package iotest.testProperties; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class TestPropertiesStore { public static void main(String[] args) throws IOException { Properties properties = new Properties(); FileOutputStream fos = new FileOutputStream("src\\iotest\\testProperties\\a.txt"); properties.setProperty("a","a1"); properties.setProperty("b","b1"); properties.setProperty("c","c1"); properties.store(fos,"copy file"); fos.close(); } }
load方法:把硬盘上的文件(文件里面存储着键值对),读取到内存集合中使用
public synchronized void load(Reader reader)
public synchronized void load(InputStream inStream)
使用步骤:
1.创建Properties集合对象
2.使用Properties集合对象中的方法load读取保存键值对的文件
3.遍历Properties集合
注意:
1.存储键值对的文件中,键与值默认的连接符号可使用=,空格(其他符号)
2.存储键值对的文件中,可以使用#进行注释,被注释的键值对不会被读取
3.存储键值对的文件中,键与值默认为字符串,不用再加“”
package iotest.testProperties; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.util.Set; public class TestPropertiesload { public static void main(String[] args) throws IOException { Properties properties = new Properties(); FileInputStream fis = new FileInputStream("src\\iotest\\testProperties\\a.txt"); properties.load(fis); Set<String> set = properties.stringPropertyNames(); for (String key : set) { System.out.println(key+"-->"+properties.getProperty(key)); } fis.close(); } }