java--Proreties
2019-08-09 00:00:00
java
Prorerties
/*
* Properties,内存与文件信息交互
* 表示了一个持久的属性集
*
* 构造方法:
* Properties()
*
*
*/
//简单使用 创建,添加,遍历,
private static void method() {
// 创建属性列表对象
Properties prop = new Properties();
//添加映射关系
prop.put("czbk001","zhangs");
prop.put("czbk002","lis");
prop.put("czbk003","wangs");
//遍历
//获取所有的key,根据key获取value
Set<java.lang.Object> keys = prop.keySet();
for(java.lang.Object key:keys)
{
java.lang.Object value = prop.get(key);
System.out.println(key+"="+value);
}
System.out.println("------");
Set<Entry<java.lang.Object, java.lang.Object>> entrys = prop.entrySet();
for(Entry<java.lang.Object, java.lang.Object> entry:entrys)
{
java.lang.Object value = entry.getValue();
java.lang.Object key = entry.getKey();
System.out.println(key + "=" + value);
}
//与IO流的结合
//保存到文件(只能接收打印流)
private static void method2() throws FileNotFoundException {
// void list(PrintWriter out)
// void list(PrintStream out)
//创建属性列表
Properties prop = new Properties();
//添加映射关系
prop.setProperty("CZBK001","zhangs");
prop.setProperty("CZBK002", "wangs");
prop.setProperty("CZBK003", "lis");
//创建打印流对象
PrintWriter out = new PrintWriter("d.txt");
//void list(PrintWriter out)
prop.list(out);
//释放资源
out.close();
}
//从文件读取到prop
private static void method3() throws FileNotFoundException, IOException {
// void load(Reader reader)
//创建属性列表对象
Properties prop = new Properties();
//创建一个输入流对象
FileReader fr = new FileReader("d.txt");
//void load(Reader reader)
prop.load(fr);
//释放资源
fr.close();
System.out.println(prop);
}
//保存到文件(任意)
//void store(Writer writer, String comments)
private static void method4() throws IOException {
// 创建属性列表对象
Properties prop = new Properties();
// 添加映射关系
prop.setProperty("CZBK001","zhangs");
prop.setProperty("CZBK002", "wangs");
prop.setProperty("CZBK003", "lis");
// 创建输出流对象
FileWriter fw = new FileWriter("e.txt");
//void store(Writer writer, String comments)
prop.store(fw, "comments message");
//释放资源
fw.close();
}
//编码问题
//如果写入文件时出现了乱码,可以尝试修改编码
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt"), "UTF-8");
String s = "你好鸭";
osw.write(s);
osw.close();
相关文章