作业:我有一个文本文件,我知道数据是键值对形式的,但是不知道内容是什么。请写一个程序判断是否有“lisi”这样的键存在,如果有就改变其值为100
思路:
1.首先读取文本文件中的内容,加载到Properties属性集合中,使用load方法
2.遍历属性集合,判断有无lisi键,如果有的话,将其值改为100
3.将Properties属性集合中的内容写入文件中,使用store方法
public class MyTest4 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
FileReader fileReader = new FileReader("user.txt");
//读取文本文件中的内容并加载到集合中
properties.load(fileReader);
fileReader.close();
//遍历属性集合
//获取所有的键的集合
Set<String> keySet = properties.stringPropertyNames();
for (String s : keySet) {
if ("lisi".equals(s)){
properties.setProperty(s,"100");
}
}
//把属性集合中的数据保存到文本文件中
FileWriter fw = new FileWriter("user.txt");
properties.store(fw,"content");
fw.close();
}
}