• java-对象序列化代码实例


     1 import java.io.ByteArrayInputStream;
     2 import java.io.ByteArrayOutputStream;
     3 import java.io.ObjectInputStream;
     4 import java.io.ObjectOutputStream;
     5 import java.io.Serializable;
     6 
     7 public class User implements Serializable {
     8     private String username;  
     9     
    10     private transient String password;  
    11       
    12     public User(String username,String password) {  
    13         this.username = username;  
    14           
    15         this.password = password;  
    16     }  
    17   
    18     @Override  
    19     public String toString() {  
    20         return username + "" + password;  
    21     }  
    22       
    23     public static void main(String[] args) throws Exception{  
    24         User user = new User("WeiDong","123456");  
    25           
    26         System.out.println("Before Serialization:" + user);  
    27           
    28         ByteArrayOutputStream buf = new ByteArrayOutputStream();  
    29         //创建一个对象输出流,通过对象输出流的writeObject()写对象到输出流中  
    30         ObjectOutputStream out = new ObjectOutputStream(buf);  
    31           
    32         out.writeObject(user);  
    33           
    34         out.close();  
    35         //创建一个对象输入流,通过对象输入流的readObject()从输入流中读取对象  
    36         ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray()));  
    37           
    38         user = (User)in.readObject();  
    39           
    40         System.out.println("After Serialization:" + user);  
    41           
    42         in.close();  
    43     }  
    44 }
    45 
    46 Before Serialization:WeiDong123456
    47 After Serialization:WeiDongnull
  • 相关阅读:
    数据恢复与硬盘数据结构
    Add dynamic tooltips to buttons in dialog(转)
    Visual C++ 2008资源全搜罗(转)
    (转)学习数据恢复(四)
    如何开启Vista Aero效果
    硬盘FAT文件系统原理的详细分析
    web form弹出提示框
    WIN32_FIND_DATA and CFileFind
    编程老手与高手的误区
    (转)解读NTFS(三)
  • 原文地址:https://www.cnblogs.com/My-Cloud/p/4487176.html
Copyright © 2020-2023  润新知