序列化
将内存中保存的对象变为二进制数据流的形式进行传输,或者是将其保存在文本中.
实现序列化与反序列化的对象操作:
ObjectOutputStream、 ObjectInputStream
Serializable默认会将对象中所有属性进行序列化保存,如果现在某些属性不希望被保存了,那么就可以 使用transient关键字。
class person implements Serializable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public person(String name, int age) {
this.name = name;
this.age = age;
}
}
public static void ser(Object obj) throws IOException, ClassNotFoundException {
try {
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(obj);
oos.close();
System.out.printf("序列化完成");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void dse() throws ClassNotFoundException {
ObjectInputStream ois= null;
try {
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test{
static File file=new File("C:\\Users\\lenovo\\Desktop\\1.txt");
public static void main(String[] args) {
// ser(new person("fay",18));
dse();
ois = new ObjectInputStream(new FileInputStream(file));
System.out.println( ois.readObject());
ois.close();
System.out.printf("反序列化完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}