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

  • Post author:
  • Post category:其他
在主方法中创建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;
	}
	@Override
	public 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;
	}
	
}


版权声明:本文为momoainuonuo原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。