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
时间: 2024-09-08 03:30:38