• java_对象序列化


    • 对象序列化(serializable)

    序列化读ObjectInputStream  ois=new ObjectInputStream(new FileInputStream("./ggg.txt"));

    序列化写: ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("./ggg.txt"));

    序列化对象参数为I/O字节流读写对象。

    1.将对象序列化写到本地

    新建学生类实现序列化接口,当对象中某一个属性或方法不需要序列化时,在属性或方法前加:transient.

    import java.io.Serializable;
    public class Student implements Serializable {
    private String name;
    transient private int age; //某一个属性不需要序列化时加:transient
    private String id;
    public void eat(){
    System.out.println("吃吃");
    }
    //这里需要添加set和get方法

    }

    创建对象,实现对象序列化写到本地文件ggg.txt

    @Test
    public void test12(){
    Student stu = new Student();
    stu.setName("序列化测试");
    stu.setAge(20);
    stu.setId("21432423");
    ObjectOutputStream oos=null;
    try {
    oos=new ObjectOutputStream(new FileOutputStream("./ggg.txt"));
    oos.writeObject(stu); //将一个对象写入到本地

    } catch (IOException e) {
    e.printStackTrace();
    }finally {
    try {
    if (oos != null) {
    oos.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    测试结果:�� sr com.lanou.Studenta��N0�� L idt Ljava/lang/String;L nameq ~ xpt 21432423t 序列化测试

    2.反序列化读,将本地文件ggg.txt文件反序列化读回计算机
    @Test
    public void test13(){

    //将序列化好的对象,读回计算机
    //反序列化

    ObjectInputStream ois=null;
    try {
    ois=new ObjectInputStream(new FileInputStream("./ggg.txt"));
    Object o=ois.readObject();
    System.out.println(o);

    } catch (IOException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }finally {
    try {
    if (ois != null) {
    ois.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    测试结果:
    Student{name='序列化测试', age=0, id='21432423'}
    
    
    Process finished with exit code 0
     

                                                                                         

  • 相关阅读:
    智慧城市顶层设计策略方案(PPT)
    ant build.xml 解释!
    Excel poi API基础教程!
    操纵Excel文件的 ExcelUtil 类 !
    在selenium测试中使用XPATH功能函数starts-with、contains、descendant、ancestor、text()定位网页元素
    [ Selenium2 从零开始 by Bruce from http://seleniumcn.cn ] 1-8 视频集锦
    selenium 概念及练习 !
    selenium Object Page 设计模式理解及实现!
    使用TestNG 和 CSV文件进行数据驱动
    如何让评审人爱上我
  • 原文地址:https://www.cnblogs.com/zhouchangyang/p/10645065.html
Copyright © 2020-2023  润新知