package com.zhu.io;
import java.io.*;
/**
* Created by idea on 2016/6/6.
* @我就是你们的小星星
*
* 对象的序列化和反序列化
*/
public class ObjectStream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
String srcPath = "d:/testio/a.txt";
String descPath = "d:/testio/a.txt";
outStream(srcPath);
readStream(descPath);
}
//反序列化
public static void readStream(String srcPath) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(srcPath)));
Person person1 = (Person) ois.readObject();
Person person2 = (Person) ois.readObject();
System.out.println(person1.getName());
System.out.println(person2.getName());
}
//序列化
public static void outStream(String descPath) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(descPath)));
oos.writeObject(new Person("竹洪鑫" , 18 , 1 , 500 ));
oos.writeObject(new Person("田启瑞" , 19 , 2 , 600));
}
}
package com.zhu.io;
import java.io.Serializable;
/**
* Created by idea on 2016/6/6.
* @我就是你们的小星星
*
* 实体类(必须实现serialzable的类才能被序列化,这个接口只是个空接口;
* 被transient标记的属性将不会被序列化)
*/
public class Person implements Serializable{
private String name;
private int age;
private transient int id ;
private int salary;
public Person() {
}
public Person(String name, int age, int id, int salary) {
this.name = name;
this.age = age;
this.id = id;
this.salary = salary;
}
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 int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}