/**
* @version
* @description
*/
package cn.xasmall.example;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* 对象与序列化
* @author 26248
*
*/
public class Serialization {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("data.txt"));
Student stu1=new Student(23, "张三", "jifan", 334.2d);
out.writeObject(stu1);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream("data.txt"));
Object student1=in.readObject();
in.close();
System.out.println(student1);
}
}
//implements Externalizable继承后序列化机制失效
class Student implements Serializable{
private static final long serialVersionUID = 1L;
//transient使序列化失效
transient private int student_id;
private String student_name;
private String student_psw;
private double student_money;
/**
* @return the student_id
*/
public int getStudent_id() {
return student_id;
}
/**
* @param student_id the student_id to set
*/
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
/**
* @return the student_name
*/
public String getStudent_name() {
return student_name;
}
/**
* @param student_name the student_name to set
*/
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
/**
* @return the student_psw
*/
public String getStudent_psw() {
return student_psw;
}
/**
* @param student_psw the student_psw to set
*/
public void setStudent_psw(String student_psw) {
this.student_psw = student_psw;
}
/**
* @return the student_money
*/
public double getStudent_money() {
return student_money;
}
/**
* @param student_money the student_money to set
*/
public void setStudent_money(double student_money) {
this.student_money = student_money;
}
public Student(int id,String name,String psw,double money) {
this.student_id=id;
this.student_name=name;
this.student_psw=psw;
this.student_money=money;
}
public String toString() {
return "student=["+student_id+","+student_name+","+student_psw+","+student_money+"]";
}
// writeObject()与readObject()两个方法使student_id再次被序列化
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(student_id);;
}
private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException {
in.defaultReadObject();
student_id=in.readInt();
}
}
java对象序列化
最新推荐文章于 2023-06-27 19:18:23 发布