java.util.Properties
继承于Hashtable
,来表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,System.getProperties
方法就是返回一个Properties
对象。
/* Student.txt文件内容:
* 刘伊=18
* 王含=20
* 李风风=17
* 刘方=16
* 马红红=20
* 丁磊=18
* 方影=21
* 姚华华=20
*/
public class Demo04 {
public static void main(String[] args) throws IOException {
File file = new File("Student.txt");
File newFile = new File("newstu.txt");
Properties properties = new Properties();
FileReader fr = new FileReader(file);
properties.load(fr);
Set<String> names = properties.stringPropertyNames();
FileWriter fw = new FileWriter(newFile);
for (String name : names) {
if (name.equals("刘方")){
properties.put("刘方",18);
}
}
properties.store(fw,null);
}
}
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at java.util.Properties.store0(Properties.java:834)
at java.util.Properties.store(Properties.java:771)
at homework.Demo04.main(Demo04.java:39)
当properties的键与值有不为String类型时,调用store方法时会出现类型不能转换为String的异常。
properties.put("刘方",18);应改为properties.put("刘方","18")