package net.csdn.blog.wdd9527.week05.day02.test04;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
/**
* 设计一个程序,使用Properties从a.properties文件中将键值对全部读取到集合中,
* 向集合中添加一个键值对后,再将新的集合中的元素全部都写入到a.properties文件中。
* @author WDD
*
*/
public class Main {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
/**
* 首先map集合的键值对都不能为基本数据类型,
* 其次,key的值也最好为字符串,不然下面写入的时候,将会写入乱码
*/
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(new File("a.properties")));
//读取a.properties内容到map集合中去
String readLine = null;
while ((readLine = br.readLine()) != null) {
String[] split = readLine.split("="); //读一行,为字符串数组
map.put(split[0], split[1]); //分别把key和value放入map集合中去
}
System.out.println(map);
map.put("0008", "huba"); //注意多次运行时,这个key的值别忘记改,不然加不进去
bw = new BufferedWriter(new FileWriter(new File("a.properties")));
Set<String> keySet = map.keySet(); //把map集合的key转换为set集合,方便遍历
for (String in : keySet) {
/**
* write(int)方法实际上是写入char类型,内存长度只有两个字节,
* 所以出现乱码,所以将int转成string后再写或者直接就定义成String类型。
*/
bw.write(in);
bw.write("=");
bw.write(map.get(in));
bw.newLine();
}
//从新读取一遍并打印,验证有没有写入成功。
String readLine1 = null;
while ((readLine1 = br.readLine()) != null) {
String[] split = readLine1.split("=");
map.put(split[0], split[1]);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
} finally {
if (br != null) {
try {
br.close();
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
.properties是java所支持的配置文件类型,
里面存的类似于都是键值对,用"="相互连接,
并且都是String类型