序列化与反序列化
package 学生管理系统; import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.util.ArrayList; import java.util.Scanner; class Student implements Serializable{ public int num; public String name,sex,obj; Student() { this.num = 0; this.name = ""; this.sex = ""; this.obj = ""; } Student(int _num ,String _name,String _sex,String _obj){ this.num = _num; this.name = _name; this.sex = _sex; this.obj = _obj; } void print(){ System.out.println("学号:"+num+" 姓名:"+name+" 性别:"+sex+" 专业:"+obj); } } public class StudentMIS { /** * @param args */ //保存 序列化 public static void save(ArrayList<Student> student){ try{ ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream("F:\\输入输出\\student.dat")); os.writeObject(student); os.close(); System.out.println("写入成功."); } catch (Exception e){ System.out.println("发生异常"+e); e.printStackTrace(); } } //显示 反序列化 public static ArrayList<Student> read(){ File f = new File("F:\\输入输出\\student.dat"); if(f.exists()){ try{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f)); ArrayList<Student> student = (ArrayList<Student>)ois.readObject(); ois.close(); System.out.println("读取成功."); return student; } catch(IOException e){ System.out.println("发生异常1"+e); e.printStackTrace(); } catch(ClassNotFoundException e){ System.out.println("发生异常2"+e); e.printStackTrace(); } } return null; } public static void main(String[] args){ ArrayList<Student> student = new ArrayList<Student>(0); student = read();//反序列化 int choose = 0; int num; String name,sex,obj; Scanner in = new Scanner(System.in); do{ System.out.println("1.增加 2.删除 3.显示 4.修改 5.保存 6.退出"); choose = in.nextInt(); switch(choose){ case 1: Student temp = new Student(); System.out.println("请输入学号:"); temp.num = in.nextInt(); System.out.println("请输入姓名:"); temp.name = in.next(); System.out.println("请输入性别:"); temp.sex = in.next(); System.out.println("请输入专业:"); temp.obj = in.next(); student.add(temp); break; case 2: System.out.print("请输入你要删除的学号"); num = in.nextInt(); for(int i=0;i<student.size();i++){ if(student.get(i).num == num){ student.remove(i); } } break; case 3: for(int i=0;i<student.size();i++){ student.get(i).print(); } break; case 4: System.out.print("请输入你要修改的学生学号"); num = in.nextInt(); int i; for(i=0;i<student.size();i++){ if(student.get(i).num == num){ System.out.println("请输入新的学号:"); student.get(i).num = in.nextInt(); System.out.println("请输入姓名:"); student.get(i).name = in.next(); System.out.println("请输入性别:"); student.get(i).sex = in.next(); System.out.println("请输入专业:"); student.get(i).obj = in.next(); System.out.println("修改成功."); } } if(i == student.size()){ System.out.println("无该学生!"); } break; case 5: save(student); break; case 6: choose = 7; break; } }while(choose >= 1 && choose <= 6 ); } }