Properties类与流的相关方法,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")