引用数据类型处理流
反序列化 输入流:ObjectInputStream readObject()
序列化 输出流:ObjectOutputStream writeObject()
注意:
1)、先序列化后反序列化;反序列化顺序必须与序列化一致
2)、不是所有的对象都可以序列化, 必须实现java.io.Serializable接口
不是所有的属性都需要序列化,用transient修饰的属性不会被序列化
代码:
*/
public class Employee implements java.io.Serializable {//实现接口
//不需要序列化
private transient String name;
private double salary;
public Employee() {
}
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
案例:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
/**
* 不是所有的對象都可以序列化 java.io.NotSerializableException
* 不是所有的屬性都需要序列化 transient
* @author Administrator
*
*/
public class ObjectDemo01 {
/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
try {
seri("e:/xp/test/ser.txt");
read("e:/xp/test/ser.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//反序列化
public static void read(String destPath) throws IOException, ClassNotFoundException{
//创建源
File src =new File(destPath);
//选择流
ObjectInputStream dis =new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(src)
)
);
//操作 读取的顺序与写出一致 必须存在才能读取
//不一致,数据存在问题
Object obj =dis.readObject();
if(obj instanceof Employee){
Employee emp=(Employee)obj;
System.out.println(emp.getName());
System.out.println(emp.getSalary());
}
obj =dis.readObject();
int[] arr=(int[])obj;
System.out.println(Arrays.toString(arr));
dis.close();
}
//序列化
public static void seri(String destPath) throws IOException{
Employee emp =new Employee("bjsxt",1000000);
int[] arr ={1,2,3,45};
//创建源
File dest =new File(destPath);
//选择流 ObjectOutputStream
ObjectOutputStream dos =new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(dest)
)
);
//操作 写出的顺序 为读取准备
dos.writeObject(emp);
dos.writeObject(arr);
//释放资源
dos.close();
}
}
小结:
注意创建对象时的写法。