序列化

    xiaoxiao2021-04-19  76

    序列化是将对象状态转换为可保持或传输的格式的过程。

    与序列化相对的是反序列化,它将流转换为对象。

    这两个过程结合起来,可以轻松地存储和传输数据。

    public static void main(String[] args)throws IOException { List<Dog> list=new ArrayList<Dog>(); Dog dog=new Dog("dd",18); Dog dog1=new Dog("dsd",18); list.add(dog); list.add(dog1); FileOutputStream fos=new FileOutputStream("E:/S2226.txt"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(list); fos.close(); oos.close(); System.out.println("序列化成功!"); }

    Dog  类

    import java.io.Serializable; public class Dog implements Serializable{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Dog(String name, int age) { super(); this.name = name; this.age = age; } public Dog() { super(); // TODO Auto-generated constructor stub }

    注意点: 01.如果自定义类需要被序列化,那么必须实现Serializable接口

    02.禁止某个属性被序列化

    使用transient修饰

    比如:

    transient public String msg

    转载请注明原文地址: https://ju.6miu.com/read-675741.html

    最新回复(0)