ObjectOutputStream ObjectInputStream
package IO.序列化反序列化;
/*
*/
import org.junit.Test;
import java.io.*;
public class ObjectInputOutputStreamTest {
//序列化
@Test
public void s1() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱你"));
oos.flush();
oos.close();
}
//反序列化
@Test
public void s2() throws IOException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
try {
Object o = ois.readObject();
String str= o.toString();
System.out.println(str);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
ois.close();
}
}
}
#对存在的对象序列化,反序列化
serialVersionUID 若不是显示声明,序列化时系统自动生成,
但是类修改时,servialVersionUID可能会改变,反序列化时找不到新的UID就实现不了反序列化
要想一个对象可序列化的:
1. Serializable
2. public static final long serialVersionUID = 12541546451L;
3. 若是序列化对象中包含其他对象,对如A包含B对象,那么B对象也是需要实现Serializable
4. 不能序列化static 和 transient修饰的成员变量(成了NULL)
代码
序列化类:Person
package IO.序列化反序列化;
import java.io.Serializable;
public class Person implements Serializable {
public static final long serialVersionUID = 12541546451L;
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(){
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Test
package IO.序列化反序列化;
import org.junit.Test;
import java.io.*;
public class PersonObjectStream {
@Test
public void t3() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new Person("hello",18));
oos.flush();
oos.close();
}
@Test
public void t4() throws IOException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
try {
Object o = ois.readObject();
Person p =(Person) o;
System.out.println(p);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
ois.close();
}
}
}
#对Peron进行添加Account对象
Account对象也需要实现序列化
package IO.序列化反序列化;
import java.io.Serializable;
public class Account implements Serializable {
public static final long serialVersionUID=4156456L;
double balance;
public Account(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"balance=" + balance +
'}';
}
}
Test
@Test
public void t3() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new Person("阿泽",18,new Account(5000)));
oos.flush();
oos.close();
}
反序列化和上述一样,没有改变