1.创建JavaBean类
public class People {
private String name;
private int age;
private char sex;
public People() {
}
public People(String name, int age, char sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
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 char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
}
创建的规则:
私有成员变量
对成员变量操作的公共get/set方法
实现Serializable接口
一定有公有无参的构造方法
2.序列化
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Serialization {
public static void main(String[] args) {
// 创建一个对象指向分配的空间并赋值
People people = new People("张三", 20, '女');
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("F:/001.txt");
//把对象转为二进制进行保存
oos = new ObjectOutputStream(fos);
//把转换后的对象保存到本地
oos.writeObject(people);
//清理内存
oos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//关流
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
3.反序列
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Deserialization {
public static void main(String[] args) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("F:/001.txt");
//把二级制文件转为类对象
ois = new ObjectInputStream(fis);
//读取二进制文件
Object obj = ois.readObject();
if (obj instanceof People) {
People people = (People) obj;
System.out.println(people);
}
} catch (EOFException e) {
// TODO: handle exception
System.out.println("已读取");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//关流
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}