java 序列化 反序列化 简单实现

来源:互联网 发布:教师网络研修的好处 编辑:程序博客网 时间:2024/05/16 08:39

若Student类仅仅实现了Serializable接口


public class Student  implements  Serializable{
    
    public String name;
    public int id;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}


测试


public class StudentTest {

    /**
     * @param args
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        
        //序列化
        Student stu  = new Student();
        stu.setId(1);
        stu.setName("yt");
        File file = new File("D:/student.txt");
        FileOutputStream   out  = new FileOutputStream(file);
        ObjectOutputStream  ob = new ObjectOutputStream(out);
        ob.writeObject(stu);
        ob.flush();
        ob.close();
        //反序列化
        FileInputStream fis = new FileInputStream(file);  
        ObjectInputStream ois = new ObjectInputStream(fis);  
        Student st1 = (Student) ois.readObject();  
        System.out.println("name = " + st1.getName());  
        ois.close();  
        fis.close();  
      
    }

}


实例2:


public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub

       
        //反序列化
        
        byte[]ter = show();  
        ByteArrayInputStream  in  = new ByteArrayInputStream(ter);
        ObjectInputStream ois = new ObjectInputStream(in);  
        Student st1 = (Student) ois.readObject();  
        System.out.println("name = " + st1.getName());  
        ois.close();  
        in.close();  

    }

    public static  byte[]  show() throws IOException{
       Student stu  = new Student();
       stu.setId(1);
       stu.setName("yt");
       ByteArrayOutputStream  out  = new ByteArrayOutputStream();
       ObjectOutputStream  ob = new ObjectOutputStream(out);
       ob.writeObject(stu);
       byte[] ter =out.toByteArray();
       try {
        ob.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
       try {
        ob.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
       return  ter;
    }
}



0 0