多个对象的二进制流文件反序列成对象及对象序列化成二进制流

package com.xiang;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


import org.junit.Test;


/**
 * 用ObjectOutputStream 将可序列化的java对象从内存中(程序都市在内存中运行的) 序列化城二进制流输出于磁盘文件中
 * 用 ObjectInputStream  将磁盘文件的二进制对象从文件中反序列输入成java对象于内存中
 * */
public class ObjectStreamDemo {
//对象序列化成二进制流
     @Test
     public void test1() throws FileNotFoundException, IOException{
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:/temp/t.txt"));
      oos.writeObject(new Student("小明", 12));
      oos.flush();
      oos.writeObject(new Student("小红", 13));
      oos.flush();
      oos.writeObject(new Student("小", 15));
      oos.flush();
     };
     //将包含多个对象的二进制流文件反序列成对象
     @Test
     public void test2() throws FileNotFoundException, IOException, ClassNotFoundException{
    FileInputStream is = new FileInputStream(new File("E:/temp/t.txt"));
    ObjectInputStream ois = new ObjectInputStream(is);
    while(is.available()>0){//表示t.txt文件中还有字节没有读取
    System.out.println(is.available());
    Student stu = (Student)ois.readObject();
    System.out.println(stu);
    }
     
     
     
     }
     

}



可序列对象

package com.xiang;


import java.io.Serializable;
/**
 * @author xiangshuai
 * 用ObjectOutputStream对象流序列化此对象必须是可序列化的即实现了Serializable接口
 * 其属性 如String name,Integer age 即String ,Integer也必须是可序列化的,即实现了Serializable接口
 * */
public class Student implements Serializable{
    /**

*/
private static final long serialVersionUID = 1L;
public String name;
    public Integer age;
public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}

}






















猜你喜欢

转载自blog.csdn.net/xiangshuai198807/article/details/79047486