目录
序列化(ObjectOutputStream)
序列化:类可以被转成二进制数据进行传输(实现Serializable接口的类可以被序列化)
ObjectOutputStream(序列化) implements OutputStream。
简单示例:
class Animal implements Serializable{
private String eat;
private String write;
public Animal() {
}
public Animal(String eat, String write) {
this.eat = eat;
this.write = write;
}
public String getEat() {
return eat;
}
public void setEat(String eat) {
this.eat = eat;
}
@Override
public String toString() {
return "eat:" + this.eat + "、write:" + this.write;
}
}
public class Demo01 {
private static final File ANIMAL_FILE = new File("D:" + File.separator + "Hello.ses");
public static void main(String[] args) throws Exception {
test();
System.out.println(detest());
}
public static void test() throws Exception {
Animal an = new Animal("饭","水");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(ANIMAL_FILE));
oos.writeObject(an);
oos.close();
}
}
反序列化 (ObjectInputStream)
通过ObjectOutputStream.readObject()才可以读取ObjectOutputStream.writeObject()输出的信息。
ObjectInputStream(序列化) implements InputStream
简单示例:
public class Demo01 {
private static final File ANIMAL_FILE = new File("D:" + File.separator + "Hello.ses");
public static void main(String[] args) throws Exception {
detest();
}
public static void detest() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ANIMAL_FILE));
Animal an = (Animal) ois.readObject();
System.out.println(an);
ois.close();
}
结果
eat:饭、write:水
实际开发中一般使用第三方的序列管理工具类,也可以变成结构化的文本传输,可以所有语言都可以用。
transient
transient:在在自动序列化的操作过程之中(一般都会自动保存),声明不需要保存的属性。
简单示例:
class Animal implements Serializable{
private transient String eat;
private transient String write;
public Animal() {
}
public Animal(String eat, String write) {
this.eat = eat;
this.write = write;
}
public String getEat() {
return eat;
}
public void setEat(String eat) {
this.eat = eat;
}
@Override
public String toString() {
return "eat:" + this.eat + "、write:" + this.write;
}
}
public class Demo01 {
private static final File ANIMAL_FILE = new File("D:" + File.separator + "Hello.ses");
public static void main(String[] args) throws Exception {
///test();
detest();
}
public static void test() throws Exception {
Animal an = new Animal("饭","水");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(ANIMAL_FILE));
oos.writeObject(an);
oos.close();
}
public static void detest() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ANIMAL_FILE));
Animal an = (Animal) ois.readObject();
System.out.println(an);
ois.close();
}
}
结果
transient:没有保存数据
eat:null、write:null