ObjectOutputStream和ObjectInputStream分别代表对象字节输出流和对象字节输入流,其功能分别是:
ObjectOutputStream:
提供了writeObject(Serializable)方法,将对象转化成字节流再输出到目标字节流中去。这一个过程称为序列化。需要序列化的类必须实现Serializable接口。
ObjectInputStream:
提供了Object readObject()方法,将字节输入流转化成对象。这一个过程称为反序列化。
示例1代码:
class Student implements Serializable{
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
public class TestObjectOutputStream {
public static void main(String[] args) {
ObjectOutputStream oos=null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream("obj.dat");
oos=new ObjectOutputStream(fos);
Student s=new Student("Jack",20);
oos.writeObject(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(oos!=null)oos.close();
if(fos!=null)fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
示例2代码:
public class TestObjectInputStream {
public static void main(String[] args) {
ObjectInputStream ois=null;
FileInputStream fis=null;
try {
fis = new FileInputStream("obj.dat");
ois=new ObjectInputStream(fis);
Student s=(Student) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
if(ois!=null)ois.close();
if(fis!=null)fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}