序列化慢慢看哦
package com.rmq.xuliehuafanxuliehua;
import java.io.Serializable;
//如果一个 类创建的对象需要被序列化,这个类必须实现Serializable接口
//Serializable 是一个标志接口吗,没任何定义 为了告诉JVM该类对象可以被序列化
// 什么时候对象需要被序列化
//1.把文件保存到文件中(存到物理介质)
//2.对象需要在网络上传输
public class Student implements Serializable{
private static final long serialVersionUID = 1L; //加上这句话更加严谨
private String name;
private String stuNo;
private String claName;
public Student() {
}
public Student(String name, String stuNo, String claName) {
super();
this.name = name;
this.stuNo = stuNo;
this.claName = claName;
}
@Override
public String toString() {
return "StudentInfo [name=" + name + ", stuNo=" + stuNo + ", claName=" + claName + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public String getClaName() {
return claName;
}
public void setClaName(String claName) {
this.claName = claName;
}
}
package com.rmq.xuliehuafanxuliehua;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class TestSerializable {
public static void main(String[] args) {
writeObject(); //序列化
readObject(); //反序列化
}
//反序列化
private static void readObject() {
File file = new File("d:/Student.txt");
try {
InputStream in = new FileInputStream(file);
ObjectInputStream oos = new ObjectInputStream(in);
Student stu = (Student) oos.readObject();
oos.close();
System.out.println(stu); //写了toString方法
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//对象序列化
/**
* 对象序列化
* 把对象写入文件:实际写入的是 类名,属性名,属性类型,属性的值
*/
private static void writeObject() {
Student stu = new Student("张三","123456","一班");
File file = new File("d:/Student.txt");
try {
OutputStream out = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(stu);
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第一次写有什么不对的请大家跟我说说哦