import java.io.*; public class JavaObjectSerializator { public static void main(String args[]) { String path = "F://文件//"; String file = "object.txt"; Student s=new Student(); s.setAge(26); s.setName("lili"); s.setDepartment("计算机"); s.setId(1); try { System.out.println(s); //写入对象 JavaObjectSerializator.serializateObjectToFile(s, path+file); //读出对 Student st=(Student)JavaObjectSerializator.readObjectFromFile(path+file); System.out.println(st); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void serializateObjectToFile(Object o,String file) throws IOException{ FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(o); oos.close(); } public static Object readObjectFromFile(String file) throws IOException, ClassNotFoundException{ Object o=null; FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); o=ois.readObject(); return o; } } class Student implements Serializable { private static final long serialVersionUID = 1L; int id; String name; int age; String department; public Student(){} // public Student(int id, String name, int age, String department) { this.id = id; this.name = name; this.age = age; this.department = department; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "{姓名:"+this.getName()+" ,院系:"+this.getDepartment()+" ,年龄:"+this.getAge()+"}"; } }