1.基本概念
将内存中保存的对象变为二进制数据流的形式进行传输,或者是将其保存在文本中。
注: 序列化对象时需要保存的就是对象中的属性,所以默认情况下对象的属性将被转化为二进制数据流存在。
2.序列化与反序列化
package 序列化;
import java.io.*;
@SuppressWarnings("serial")
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test {
public static final File file = new File("C:"+File.separator+"Users"+File.separator+
"mcc"+File.separator+"Desktop"+File.separator+"java.txt");
public static void main(String[] args) throws IOException, ClassNotFoundException {
//ser(new Person("zhangsan", 25));//序列化操作
dser();//反序列化操作
}
private static void dser() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
System.out.println(ois.readObject());
ois.close();
}
private static void ser(Person obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(obj);
oos.close();
}
}
3.transient关键字
由于Serializable默认会将对象中所有属性进行序列化保存,如果现在某些属性不希望被保存了,那么就可以使用transient关键字。
package 序列化;
import java.io.*;
@SuppressWarnings("serial")
class Person implements Serializable {
private transient String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test {
public static final File file = new File("C:"+File.separator+"Users"+File.separator+
"mcc"+File.separator+"Desktop"+File.separator+"java.txt");
public static void main(String[] args) throws IOException, ClassNotFoundException {
//ser(new Person("zhangsan", 25));//序列化操作
dser();//反序列化操作
}
private static void dser() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
System.out.println(ois.readObject());
ois.close();
}
private static void ser(Person obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(obj);
oos.close();
}
}