Java Io 对象序列化和反序列化
Java 支持将任何对象进行序列化操作,序列化后的对象文件便可通过流进行网络传输。
1. 对象序列化就是将对象转换成字节序列,反之叫对象的反序列化
2. 序列化流ObjectOutputStream
3. 反序列化流 OjbectInputStream
4. 序列化的对象必须实现一个接口 Serializable
5. 如果在对象中不想序列化某个字段,那么可以在该字段中添加transient关键字
6. 对子类进行序列化操作时,父类的构造函数会被递归调用
7. 对子类进行反序列操作时,如果父类没有实现序列化接口那么父类的构造函数会被调用
写一个将Users对象序列化和反序列化的事例:
package com.dcz.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; public class ObjectSerializableDemo { public static void main(String[] args) throws Exception { // 序列化对象 File writeObjectFile = new File("d:\\users.dat"); if(!writeObjectFile.exists()){ writeObjectFile.createNewFile(); } OutputStream fileOutputStream = new FileOutputStream(writeObjectFile); ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream); Users user = new Users("admin","123456","管理员用户"); oos.writeObject(user); oos.flush(); oos.close(); // 反序列化对象 File readerObjectFile = new File("d:\\users.dat"); InputStream fileInputStream = new FileInputStream(readerObjectFile); ObjectInputStream ois = new ObjectInputStream(fileInputStream); Users user2 = (Users)ois.readObject(); System.out.println(user2); } }
package com.dcz.io; import java.io.Serializable; public class Users implements Serializable{ private static final long serialVersionUID = 4345979997811128454L; private String username; private String password; private String describe; public Users(){} public Users(String username, String password, String describe) { super(); this.username = username; this.password = password; this.describe = describe; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDescribe() { return describe; } public void setDescribe(String describe) { this.describe = describe; } @Override public String toString() { return "Users [username=" + username + ", password=" + password + ", describe=" + describe + "]"; } }
如果不想默认序列化,想自定义序列化操作和反序列化操作就添加方法
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // 在这里做处理序列化 }
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // 在这里做处理反序列化 }