zoukankan      html  css  js  c++  java
  • Java—IO流 对象的序列化和反序列化

    • 序列化的基本操作

      1.对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化。

      2.序列化流(ObjectOutputStream),writeObject 方法用于将对象写入输出流中;

      反序列化流(ObjectInputStream),readObject 方法用于从输入流中读取对象。

      3.序列化接口(Serializeable)

      对象必须实现序列化接口,才能进行序列化,否则会出现异常。这个接口没有任何方法,只是一个标准。

    package com.test.io;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class ObjectSerialzeTest {
        /**
         * 对象的序列化
         * @param file
         * @throws Exception
         */
        public void ObjectOutput (String file) throws Exception {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            Student stu = new Student("002", "张四", 12);
            oos.writeObject(stu);
            oos.flush();
            oos.close();
        }
        /**
         * 对象的反序列化
         * @param file
         * @throws Exception
         */
        public void ObjectInput(String file) throws Exception {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            Student stu =  (Student)ois.readObject();
            System.out.println(stu.toString());
            ois.close();
        }
    
        public static void main(String[] args)  throws Exception {
            String file = "F:\javaio\obj.dat";
            ObjectSerialzeTest ost = new ObjectSerialzeTest();
            ost.ObjectOutput(file);
            ost.ObjectInput(file);
        }
    }
  • 相关阅读:
    [收藏]成大事必备9种能力9种手段9种心态
    招聘第一位网站编辑
    买了两本书
    并行计算Brahma :LINQtoGPU
    PostSharp 1.0 RTM发布了
    .NET StockTrader 2.0 新版本
    Windows Communication Foundation FAQ
    SQL Server 2008基于策略的管理
    WCF 性能基准报告
    ADO.NET实体框架连接串引发的异常:Unable to load the specified metadata resource
  • 原文地址:https://www.cnblogs.com/tianxintian22/p/6852284.html
Copyright © 2011-2022 走看看