public class Test1 { private static Person person; public static void main(String[] args) { List<Person> list = new ArrayList<Person>(); for (int i = 0; i < 10; i++) { person = new Person(); person.setAge("2" + i); person.setName("我是誰" + i); list.add(person); } writeObjectToFile(list); List<Person> lists = readObjectFromFile(); System.out.println(lists.get(0)); System.out.println(lists.size()); } public static <T> void writeObjectToFile(List<T> list) { File file = new File("test.dat"); FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(list); objOut.flush(); objOut.close(); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") public static <T> List<T> readObjectFromFile() { File file = new File("test.dat"); FileInputStream in; List<T> object = null; try { in = new FileInputStream(file); ObjectInputStream objIn = new ObjectInputStream(in); object = (List<T>) objIn.readObject(); objIn.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return (List<T>) object; } }
package com.zdy.test; import java.io.Serializable; public class Person implements Serializable { private String name; private String 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; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }