###题目描述:
读取指定目录下的 student.txt 文件,学生姓名和年龄是以 ”键值对” 形式存在的,student.txt文件内容类似如下:
张三=20
李四=19
王五=20
赵六=18
吴七=21
钱八=23
小明=22
利用 Properties 类的相关知识,将文件内容读取到项目中,判断 ”键值对” 中是否有”刘方”的数据,如果有,将其对应的年龄改为 18。并且利用 Properties 类的相关知识把修改后的最新数据写入到新文件 newstudent.txt 文件中。
###输入描述:
文件路径,例如:D:/data/file/
###输出描述:
D:/data/file/newstudent.txt
###输入例子:
D:/data/file/
其中,目录下student.txt内容如下:
XX=20
YY=19
刘方=20
ZZ=18
###输出例子:
D:/data/file/newstudent.txt
其中,newstudent.txt内容如下:
XX=20
YY=19
刘方=18
ZZ=18
package cn.tedu.io;
import java.io.*;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入源文件路径:");
String fromPath = sc.nextLine();
System.out.println("请输入输出文件路径:");
String outPath = sc.nextLine();
Properties properties = new Properties();
FileInputStream reader = new FileInputStream(fromPath);
//解决乱码问题
InputStreamReader inputStreamReader = new InputStreamReader(reader, "GBK");
properties.load(inputStreamReader);
reader.close();
Set<String> sets= properties.stringPropertyNames();
for (String key : sets){
//判断并修改对应的value
if ("刘方".equals(key)){
properties.setProperty(key, "18");
break;
}
}
Writer writer = new FileWriter(outPath);
properties.store(writer, null);
writer.close();
}
}
展示结果
输出结果: