Step1:创建一个实现了Serializable接口的类
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 172447632608611914L;
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
System.out.println("Inside Person's Constructor");
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Step2:通过ObjectOutputStream对象序列化保存数据
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class WritePerson {
public static void main(String[] args) throws IOException {
FileOutputStream outFile = null;
ObjectOutputStream out = null;
try {
String path = "src/myPerson.bin";
outFile = new FileOutputStream(path);
out = new ObjectOutputStream(outFile);
Person person = new Person("张三", 20);
out.writeObject(person);
System.out.println("序列化对象成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outFile != null)
outFile.close();
if (out != null)
out.close();
}
}
}
Step3:通过ObjectInputStream对象反序列化数据为实例对象
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ReadPerson {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
String path = "src/myPerson.bin";
FileInputStream fileIn = null;
ObjectInputStream in = null;
try {
fileIn = new FileInputStream(path);
in = new ObjectInputStream(fileIn);
Person person = (Person) in.readObject();
if (person != null) {
System.out.println(person);
} else {
System.out.println("反序列化对象失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileIn != null)
fileIn.close();
if (in != null)
in.close();
}
}
}