java序列化 教程

科技资讯 投稿 5700 0 评论

java序列化 教程

序列化的 条件:

1. 该对象必须实现 java.io.Serializble 接口

 

序列化的定义:

 

反序列化的定义:

 

为什么要序列化?

 

定义 student 类 并 实现了 java.io.Serializble 接口

public class studentDemo implements java.io.Serializable { public String name; public int phone; public String address; public String getName( { return name; } public void setName(String name { this.name = name; } public int getPhone( { return phone; } public void setPhone(int phone { this.phone = phone; } public String getAddress( { return address; } public void setAddress(String address { this.address = address; } }

 

------序列化------

序列化 需要用到 FileOutputStream( 文件输出流  和 ObjectOutputStream( 对象输出流 

 

public class SerializeDemo {
    public static void main(String[] args {
        studentDemo stu = new studentDemo(; 
        stu.setName("张三";
        stu.setPhone( 1233467733 ;
        stu.setAddress("江西";

        try {
            FileOutputStream fileOut = new FileOutputStream("student" + stu.name + ".ser"; // 创建 文件路径、文件名字
            ObjectOutputStream out = new ObjectOutputStream(fileOut; // 创建 对象输出流系统
            out.writeObject( stu ; // 写入需要的对象名
            fileOut.close(; // 关闭文件流
            out.close(; // 关闭对象输入流

            System.out.println( "---序列化对象成功---" ;

        } catch ( IOException e {
            e.printStackTrace(; // 出现异常 初始化try
        }
    }
}

 

反序列化是将 序列化的文件的内容读取出来的过程,和序列化是相对的

 

public class UnSerializble { public static void main(String[] args { String name = "张三"; try { FileInputStream fileInt = new FileInputStream("student" + name + ".ser"; // 创建文件输入流 ObjectInputStream ois = new ObjectInputStream( fileInt ; // 创建对象输入流 studentDemo stu = (studentDemo ois.readObject(; // 读取的对象强制成为 studentDemo 类 System.out.println("---反序列化内容---"; System.out.println( "name:" + stu.getName( ; System.out.println( "phone:" + stu.getPhone(; System.out.println( "address:" + stu.getAddress(; fileInt.close(; ois.close(; } catch (IOException e { throw new RuntimeException(e; } catch (ClassNotFoundException e { throw new RuntimeException(e; } } }

 

编程笔记 » java序列化 教程

赞同 (31) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽