序列化和反序列化的应用
程序员文章站
2022-05-14 17:22:27
...
新建一个Student
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int gae;
private String sex;
public Student() {
}
public Student(String name, int gae, String sex) {
this.name = name;
this.gae = gae;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGae() {
return gae;
}
public void setGae(int gae) {
this.gae = gae;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
创建一个测试类
序列化以及反序列化
import java.io.*;
public class TestStu {
public static void main(String[] args){
//调用一下
m1();
//反序列化操作
Student s=null;
try {
FileInputStream fp = new FileInputStream(“a.txt”);
ObjectInputStream ob = new ObjectInputStream(fp);
//读取一个对象
s=(Student) ob.readObject();
//释放资源
ob.close();
fp.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Employee class not found");
e.printStackTrace();
}
//无异常直接输出
System.out.println("Name:"+s.getName());
System.out.println("Age:"+s.getGae());
System.out.println("Sex:"+s.getSex());
}
public static void m1() throws IOException {
//创建序列化对象
Student s=new Student("武大郎",13,"男");
ObjectOutputStream ob = new ObjectOutputStream(new FileOutputStream("a.txt"));
ob.writeObject(s);
ob.close();
}
}
上一篇: Laravel如何加密一个值