Skip to content

Instantly share code, notes, and snippets.

@lixingcong
Last active June 5, 2016 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lixingcong/29def1c6995fe88ad68d37b761154087 to your computer and use it in GitHub Desktop.
Save lixingcong/29def1c6995fe88ad68d37b761154087 to your computer and use it in GitHub Desktop.
java.io.Serializable Sample
package seq;
public class Employee {
public String name;
public int age;
}
package seq;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
//A no-arg constructor must be accessible to the subclass that is serializable.
//序列化必须是没有参数的构造函数,因此要在对象外部进行赋值
//需要重写readObject和writeObject方法
public class Employee_seq extends Employee implements Serializable {
private static final long serialVersionUID = 1L;
private void writeObject(ObjectOutputStream o) throws IOException {
o.writeObject(this.name);
o.writeObject(this.age);
}
private void readObject(ObjectInputStream o) throws IOException, ClassNotFoundException {
this.name = (String) o.readObject();
this.age = (int) o.readObject();
}
}
package seq;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello!");
Employee_seq e = new Employee_seq();
e.name = "hello";
e.age = 12;
try {
FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.flush();
out.close();
fileOut.close();
System.out.println("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
// 反序列化
Employee_seq f = null;
try {
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
// 该readObject要求构造函数必需是无参数的。否则readobject no valid constructor
f = (Employee_seq) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + f.name);
System.out.println("Age: " + f.age);
}
}
hello!
Serialized data is saved in /tmp/employee.ser
Deserialized Employee...
Name: hello
Age: 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment