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


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();
	}

}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐