您的位置:首页 > 编程语言 > Java开发

JAVA基础对象的序列化与反序列化

2018-01-25 09:23 239 查看
对象类

package com.job.io;
import java.io.Serializable;
public class Student implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2517802070568447027L;
private String name;
private int score;
private transient String vanlaentne;

public String getVanlaentne() {
return vanlaentne;
}

public void setVanlaentne(String vanlaentne) {
this.vanlaentne = vanlaentne;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getScore() {
return score;
}

public void setScore(int score) {
this.score = score;
}

}


序列化与反序列化
package com.job.io;

import java.io.*;
import java.security.GeneralSecurityException;

import javax.security.auth.Subject;
import javax.swing.plaf.synth.SynthSeparatorUI;

public class SerializableDemo {
/*
* 对象序列化?将对象的状态持久化(文件,网络)的过程。一般是二进制流。
* 对象反序列化?把二进制还原成对象的过程。
* ObjectOutputStream:从对象转换为流
* 注意:Serializable接口没有任何方法和属性,就叫标记接口。
* ObjectInputStream:流转换为对象
* */
public static void main(String[] args) throws IOException, ClassNotFoundException {
File file = new File("serializable.txt");
//1,创建一个序列化流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("serializable.txt"));
//2,创建一个要被序列化的对象
Student st=new Student();
st.setName("赵云");
st.setScore(99);
st.setVanlaentne("貂蝉");
//3,序列化对象:writeObjec(Object obj) 将指定的对象写入ObjectOutputStream
oos.writeObject(st);
//4,释放资源
oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Student obj=(Student)ois.readObject();
ois.close();
System.out.println(obj.getName()+"战力值:"+obj.getScore()+"丨情人:保密"+obj.getVanlaentne());
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  序列化与反序列