后缀名:properties
按照键值对的顺序存储
归属于Map集合
properties是一个双列集合集合,拥有Map集合所有的特点。
重点:有一些特有的方法,可以把集合中的数据,按照键值对的形式写到配置文件当中。
也可以把配置文件中的数据,读取到集合中来。
Properties作为双列集合的方法
package com.itheima.myiotest9;
import java.util.Properties;
public class Test1 {
public static void main(String[] args) {
/*
Properties作为Map集合的操作
*/
//1.创建集合的对象
Properties prop = new Properties();
//2.添加数据
//细节:虽然我们可以往Properties当中添加任意的数据类型,但是一般只会往里面添加字符串类型的数据
prop.put("aaa","111");
prop.put("bbb","222");
prop.put("ccc","333");
prop.put("ddd","444");
//3.遍历集合
/*Set<Object> keys = prop.keySet();
for (Object key : keys) {
Object value = prop.get(key);
System.out.println(key + "=" + value);
}*/
/* Set<Map.Entry<Object, Object>> entries = prop.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + "=" + value);
}*/
}
}
Properties中特有的读写方法
public synchronized void load(Reader reader) 读取本地Properties文件里面的数据public void store(Writer writer, String comments) 把集合中的数据以键值对的形式写到本地文件当中
package com.itheima.myiotest9;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Test2 {
public static void main(String[] args) throws IOException {
/*
Properties跟IO流结合的操作
*/
//1.创建集合
Properties prop = new Properties();
//2.添加数据
prop.put("aaa","bbb");
prop.put("bbb","ccc");
prop.put("ddd","eee");
prop.put("fff","iii");
//3.把集合中的数据以键值对的形式写到本地文件当中
FileOutputStream fos = new FileOutputStream("myiotest\\a.properties");
prop.store(fos,"test");
fos.close();
/*BufferedWriter bw = new BufferedWriter(new FileWriter("myiotest\\a.properties"));
Set<Map.Entry<Object, Object>> entries = prop.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
Object key = entry.getKey();
Object value = entry.getValue();
bw.write(key + "=" + value);
bw.newLine();
}
bw.close();*/
}
}
package com.itheima.myiotest9;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Test3 {
public static void main(String[] args) throws IOException {
//1.创建集合
Properties prop = new Properties();
//2.读取本地Properties文件里面的数据
FileInputStream fis = new FileInputStream("myiotest\\a.properties");
prop.load(fis);
fis.close();
//3.打印集合
System.out.println(prop);
}
}