码迷,mamicode.com
首页 > 其他好文 > 详细

利用ObjectInputStream、ObjectOutputStream序列化多个对象

时间:2015-05-15 15:31:17      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

内容:序列化多个对象,利用一个容器存储你要序列化的多个对象。


class Student implements java.io.Serializable{
	private String name;
	
	public Student(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

public class Serializable {
	public static final File file = new File(System.getProperty("user.dir") + 
			File.separator + "data" + File.separator + "student.txt");
	
	public static void doWrite(List<Student> list) throws FileNotFoundException, IOException {
		if (file.exists() == false)
			file.createNewFile();
		
		ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file, true));
		output.writeObject(list);
		
		output.flush();
		output.close();
	}
	
	public static void doRead() throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
		List<Student> list = (List<Student>) input.readObject();
		System.out.println(list.size());
		for (Student i : list)
			System.out.println(i.getName());

		input.close();
	}
	
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("asds"));
		list.add(new Student("base"));
		doWrite(list);
		doRead();
	}

}


利用ObjectInputStream、ObjectOutputStream序列化多个对象

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45745133

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!