处理流:对象流:除了能处理基本数据和字符串外,还包括各种对象。
* 用法:和数据流一样,先写出后读取,顺序一致;不是所有的对象都可以序列化,必需实现java.io.serializable接口。
* objectOutPutStream:序列化:对象写出到文本、数据库或内存(字节数组)中。
* objecInPutStream:反序列化:将序列化之后的还原为对象。
自定义的对象需要实现java.io.Serializable接口
class Dog implements java.io.Serializable{
private int age;
private String coloer;
//private transient String coloer; 加了transient不会被序列化
public Dog(int age, String coloer) {
this.age = age;
this.coloer = coloer;
}
public String shout(){
return "汪汪";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColoer() {
return coloer;
}
public void setColoer(String coloer) {
this.coloer = coloer;
}
}
字节数组之间的序列化
public static void test() throws IOException, ClassNotFoundException {
//写出---序列化
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
//操作数据类型+数据
oos.writeChar(12);//int
oos.writeUTF("nihao");//String
//对象 String,Date这两个类都实现了java.io.Serializable
oos.writeObject("字符串对象");
oos.writeObject(new Date());
Dog dog = new Dog(2,"黄色");
oos.writeObject(dog);
oos.flush();//要刷新一下,不刷新可能会报EOFException错误
byte[] datas = baos.toByteArray();
//读取---反序列化
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
new ByteArrayInputStream(datas)));
//顺序与读取一致,不然会报EOFException错误
int a = ois.readChar();
String s = ois.readUTF();
Object str = ois.readObject();
Object date = ois.readObject();
Object d = ois.readObject();
System.out.println();
if(str instanceof String){
String sObject = (String)str;
System.out.println(sObject);
}
if(date instanceof Date){
Date dateObject = (Date)date;
System.out.println(dateObject);
}
if(d instanceof Dog){
Dog dogObject = (Dog) d;
System.out.println(dogObject.getColoer()+"---"+dogObject.shout());
}
}
结果:
字符串对象
Wed Mar 13 17:53:05 CST 2019
黄色---汪汪
文件之间的序列化
public static void test1() throws IOException, ClassNotFoundException {
//写出---序列化
ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("objectTest.txt"));
//操作数据类型+数据
oos.writeChar(12);//int
oos.writeUTF("nihao");//String
//对象 String,Date这两个类都实现了java.io.Serializable
oos.writeObject("字符串对象");
oos.writeObject(new Date());
Dog dog = new Dog(2,"黄色");
oos.writeObject(dog);
oos.flush();//要刷新一下,不刷新可能会报EOFException错误
oos.close();
//读取---反序列化
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(
new FileInputStream("objectTest.txt")));
//顺序与读取一致,不然会报EOFException错误
int a = ois.readChar();
String s = ois.readUTF();
Object str = ois.readObject();
Object date = ois.readObject();
Object d = ois.readObject();
System.out.println();
if(str instanceof String){
String sObject = (String)str;
System.out.println(sObject);
}
if(date instanceof Date){
Date dateObject = (Date)date;
System.out.println(dateObject);
}
if(d instanceof Dog){
Dog dogObject = (Dog) d;
System.out.println(dogObject.getColoer()+"---"+dogObject.shout());
}
}