java 中序列化多个对象在反序列化中如何将他们分别分离出来?

Ivan_梦方舟 2016-08-19 11:22:32
如图,我实例化两个对象,一个学生基本信息的对象,还有一个HashMap的对象(用于存放科目和相应的学生成绩),分别序列化这两个对象到stuinfo.txt 这一个文件里头,,反序列的时候我怎么分别把他们拿出来呢???求各位大神指教!!!!

...全文
326 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
rickylin86 2016-08-19
  • 打赏
  • 举报
回复

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;


import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import static java.nio.file.StandardOpenOption.*;


public class Test{
	public static void main(String[] args){
		writeObject();
		readObject();
	}

	private static void writeObject(){
		Student student = new Student(123,"张三",200502);
		HashMap<String,Integer> scores = new HashMap<>();
		scores.put("java",96);
		scores.put("c++",86);
		scores.put("C#",90);

		try(ObjectOutputStream out = new ObjectOutputStream(
											Files.newOutputStream(path,CREATE,WRITE));){
			out.writeObject(student);
			out.writeObject(scores);
		}catch(IOException e){
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	@SuppressWarnings("unchecked")
	private static void readObject(){
		try(ObjectInputStream in = new ObjectInputStream(
										Files.newInputStream(path,READ));){
			Student student = (Student)(in.readObject());
			HashMap<String,Integer> scores = (HashMap<String,Integer>)(in.readObject());
			System.out.println(student);
			Set<String> keySet = scores.keySet();
			Iterator<String> courses = keySet.iterator();
			String course = null;
			int score = 0;
			while(courses.hasNext()){
				course = courses.next();
				score = scores.get(course);
				System.out.printf("[%s:%d]",course,score);
			}
		}catch(IOException|ClassNotFoundException e){
			e.printStackTrace();
			System.exit(1);
		}
	}


	private static Path path = Paths.get(System.getProperty("user.dir")).resolve("studentInfo.bin");
}

class Student implements Serializable{
	
	private static final long serialVersionUID = 1L;

	public Student(int sno,String name,int id){
		this.sno = sno;
		this.name = name;
		this.id = id;
	}

	@Override
	public String toString(){
		return String.format("Student[sno:%d,name:%s,id:%d]",sno,name,id);
	}

	private int sno;
	private String name;
	private int id;
}
abc优希 2016-08-19
  • 打赏
  • 举报
回复
写入的是二进制文件,用readObject方法读出对象,然后转化成实际对象HashMap或者Student
肃穆丶 2016-08-19
  • 打赏
  • 举报
回复
我也是新手。。。 重新写出来应该可以 先 重写toString 方法,在遍历把他们输出出来。

62,625

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧