import java.io.*;
public class ObjectFile {
public static void main(String[] args) throws IOException {
//xuliehua();
fanxuliehua();
}
/**
* 反序列化
*/
private static void fanxuliehua() throws IOException {
ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("bb/b/o.txt"));
try {
Object o = objectInputStream.readObject();
objectInputStream.close();
System.out.println(o.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 序列化
*/
public static void xuliehua() throws IOException {
Dog dog = new Dog("mimi",12);
ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("bb/b/o.txt"));
objectOutputStream.writeObject(dog);//将对象写入序列化文件中存储起来
objectOutputStream.close();
}
}
//需要序列化的类,必须实现Serializable接口
class Dog implements Serializable {
private static final long serialVersionUID =1L; //防止序列化后,由于类的改变引起InvialidClassException;
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + 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;
}
}
网友评论