获取当前文件所在项目的绝对路径
new File("").getAbsolutePath()
需要理解的是问什么需要序列化
序列化的方式
serialVersionUID的作用
使用实例:
public class Person implements Serializable {
// private static final long serialVersionUID = -5809452578272945389L;
/**
* 防止 类反序列的时候 local class incompatible 报类不兼容的错误.
* 出发真的时版本有变化,这里就需要改版本的编号的值 serialVersionUID
* 我们只要保证在同一个类中,不同版本根据兼容需要,是否更改SerialVersionUid即可
* 系统自动生成时
* 是根据类的结构产生的hash值。增减一个属性、方法等,都可能导致这个值产生变化
*/
private static final long serialVersionUID = 1L;
private int age;
private String name;
private String sex;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
import org.junit.Test;
import java.io.*;
import static org.junit.Assert.*;
/**
* 测试类的序列化和反序列化
*/
public class PersonTest {
public String getCurlPath(){
String url = new File("").getAbsolutePath();
System.out.println("url="+ url );
return url;
}
/**
* Description: 序列化Person对象
*/
@Test
public void SerializePerson() throws FileNotFoundException,
IOException {
Person person = new Person();
person.setName("gacl");
person.setAge(25);
person.setSex("男");
// ObjectOutputStream 对象输出流,将Person对象存储到E盘的Person.txt文件中,完成对Person对象的序列化操作
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(
new File( getCurlPath() + "/testfile/Person.txt")));
oo.writeObject(person);
System.out.println("Person对象序列化成功!");
oo.close();
}
/**
* Description: 反序列Perons对象
*/
@Test
public void DeserializePerson() throws Exception, IOException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
new File(getCurlPath() + "/testfile/Person.txt")));
Person person = (Person) ois.readObject();
System.out.println("Person对象反序列化成功!"+ person.toString() );
}
}
参考文档:
java 序列化和反序列化
https://www.cnblogs.com/niceyoo/p/10596657.html
Java中serialVersionUID的解释及两种生成方式的区别
https://blog.youkuaiyun.com/xuanxiaochuan/article/details/25052057