Properties格式的文件是可以储存键值对(key-value)的,因此,我们在读取Properties格式的文件时,需要先用InputStream输入流来读取它,然后创建Properties类的对象,通过load()方法将“输入流”加载至Properties集合对象中,然后就可以在Properties格式的文件中根据键(key)获取相应的值了,也可以直接读取Properties格式的文件。
具体实现代码如下:
package com.hpc.wyj04;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Decorator05 {
public static void main(String[] args) {
//Properties格式文件的读取
//创建输入流
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("c:\\hpc\\wyj.properties"))) {
Properties props=new Properties();
props.load(bis); //将“输入流”加载至Properties集合对象中
//根据key,获取value
System.out.println(props.get("a"));
System.out.println(props.get("b"));
System.out.println(props);
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果如下:
我们已经知道Properties格式的文件是可以存储键值对(key-value)的,那我们在给Properties格式的文件中写入键值对(key-value)时应该怎样做呢?其实呢,我认为和Map是类似的,我们首先要创建一个Properties对象,然后可以直接使用put()方法放入键值对(key-value),然后使用输出流(OutputStream)来指定写入的路径,用store()方法写入,还可以为首行加上内容(以#开头)。
具体实现代码如下:
package com.hpc.wyj04;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
* 给Properties文件中写入K—V键值对
* @author 我
*
*/
public class Decorator06 {
public static void main(String[] args) {
//Properties格式文件的写入
try {
Properties props=new Properties();
props.put("a1", "123");
props.put("a2", "234");
props.put("a3", "456");
props.put("a4", "789");
//使用”输出流“,将Properties集合中的K—V键值对,写入*.Properties文件
try (BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("c:\\hpc\\wyj1.properties"))) {
// props.save(bos, "just do it");
props.store(bos, "just do it");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果如下: