编写一个程序,运行java控制台程序,检测本地是否保存学生对象(反序列化),如果保存,则输出学生信息;如果没有保存,则通过学生类Student创建一个学生对象,将学生信息输出并保存到本地文件(序列化)中

解决方案 »

  1.   

    package com.test;import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;public class Student implements Serializable{
    private static final long serialVersionUID = 1L;

    private String name; public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    }

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    /*
     * 文件为E盘下的student.txt文件
     */
    ObjectOutputStream output = null;
    Object obj = null;

    //如果捕获到异常,说明文件中没有存储任何对象
    try{
    ObjectInputStream  input  = new ObjectInputStream(new FileInputStream(new File("E:\\student.txt"))); 
    obj = input.readObject();
    } catch(Exception EOFException){
    System.out.println("没有存储学生对象");

    System.out.println(obj);
    if(obj instanceof Student){
    //如果没有异常并且存储的为学生对象
    Student student = (Student)obj;
    System.out.println("已保存的学生的姓名为: " + student.getName());
    }else {
    //如果没有异常但存储的不是学生对象
    Student s = new Student();
    s.setName("张三");
    output = new ObjectOutputStream(new FileOutputStream(new File("E:\\student.txt")));
    output.writeObject(s);
    System.out.println("学生信息已保存");
    }
    }
    }