对象流的源码
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
/*
* 对象流:
* 1先写出后读取
* 2读取的顺序和写出保持一致
* 3不是所有的对象都可以序列化Serializable
*/
public class ObjectTest2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(baos));
oos.writeUTF("我太难了");
oos.writeInt(18);
oos.writeBoolean(false);
//加入对象
oos.writeObject("希望世界和平");
oos.writeObject(new Date());
Employee emp=new Employee("小二",400);
oos.writeObject(emp);
oos.flush();
byte[] datas=baos.toByteArray();
ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
String msg=ois.readUTF();
int age=ois.readInt();
boolean flag=ois.readBoolean();
Object str=ois.readObject();
Object date=ois.readObject();
Object employee=ois.readObject();
//接下来我们就将类型还原,这里我们必须加上类型转换
if(str instanceof String) {
String strObj=(String)str;
// System.out.println(strObj);
}
if(date instanceof Date) {
Date dateObj=(Date)date;
// System.out.println(dateObj);
}
if(employee instanceof Employee) {
Employee empObj=(Employee)employee;
// System.out.println(empObj.getName()+"-->"+empObj.getSalary());
}
// System.out.println(msg);
}
}
//写了一个javabean类 后期用来封装数据 transient
class Employee implements java.io.Serializable{
private transient String name;
private double salary;
public Employee() {
}
public Employee(String name, double salary) {
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;
}
}