zoukankan      html  css  js  c++  java
  • 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
     

                                                                                         

  • 相关阅读:
    NTC温度检测程序(转)
    基于GPS的经纬度、方位角、距离、航向计算及基于单目视觉的距离计算!
    GPS速度和航向计算(转)
    NOR、 NAND、Raw Flash和 Managed Flash的区别(转)
    FreeModbus V1.6 主机使用说明(转)
    只要单片机具有真正唯一ID,就可以让加密坚不可摧(转)
    Java 给Word添加数字签名
    Java 获取Word中指定图片的坐标位置
    C#/VB.NET 自定义PPT动画路径
    在线编辑Excel——插入图表
  • 原文地址:https://www.cnblogs.com/zhouchangyang/p/10645065.html
Copyright © 2011-2022 走看看