在主方法中创建map集合中存储3个学生对象.key使用字符串表示编号(不能重复)value是学生对象。然后调用以下两个方法;

来源:互联网 发布:radeon pro 580windows 编辑:程序博客网 时间:2024/06/05 03:46
在主方法中创建map集合中存储3个学生对象.key使用字符串表示编号(不能重复)value是学生对象。然后调用以下两个方法;
1.写一个方法实现把map结合中的数据写出到文本上.(这是在仿出properties类的list方法)

2.写一个方法实现把文本上的map集合数据读出来再添加到map集合中.(这是在仿出properties类的load方法)

import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.OutputStreamWriter;import java.io.PrintStream;import java.io.Serializable;import java.util.HashMap;import java.util.Map.Entry;import java.util.Set;public class Work05 {@SuppressWarnings("resource")public static void main(String[] args) throws IOException, ClassNotFoundException {//5.在主方法中创建map集合中存储3个学生对象.key使用字符串表示编号(不能重复)value是学生对象。然后调用以下两个方法;//1.写一个方法实现把map结合中的数据写出到文本上.(这是在仿出properties类的list方法)//2.写一个方法实现把文本上的map集合数据读出来再添加到map集合中.(这是在仿出properties类的load方法)//method01();method02();}private static void method02() throws IOException, FileNotFoundException, ClassNotFoundException {ObjectInputStream ob = new ObjectInputStream(new FileInputStream("Student.txt"));Object re = ob.readObject();HashMap<String, Student> m = (HashMap<String, Student>) re;Set<Entry<String, Student>> entrySet = m.entrySet();for (Entry<String, Student> entry : entrySet) {//第一种System.out.println("学号:"+entry.getKey()+",姓名:"+entry.getValue().getName()+",年龄"+entry.getValue().getAge());//第二种,直接输出System.out.println(entry);}}//存入学生对象private static void method01() throws IOException, FileNotFoundException {HashMap<String, Student> hm = new HashMap<String,Student>();hm.put("001", new Student("小苍", "18"));hm.put("002", new Student("小智", "45"));hm.put("003", new Student("小莫", "56"));ObjectOutputStream ob = new ObjectOutputStream(new FileOutputStream("Student.txt"));ob.writeObject(hm);ob.close();}}class Student implements Serializable{/** *  */private static final long serialVersionUID = -1013735523655706385L;String name;String age;public Student(String name, String age) {super();this.name = name;this.age = age;}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + "]";}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public static long getSerialversionuid() {return serialVersionUID;}}


阅读全文
1 0
原创粉丝点击