本文主要是介绍利用ObjectInputStream、ObjectOutputStream序列化多个对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
内容:序列化多个对象,利用一个容器存储你要序列化的多个对象。
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序列化多个对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!