zoukankan      html  css  js  c++  java
  • 34.4 对象流 ObjectOutputStream ObjectInputStream

    * 对象操作流:可以用于读写任意类型的对象
    * ObjectOutputStream
    *    writeObject
    *    ObjectOutputStream(OutputStream out)
    * ObjectInputStream
    *    readObject
    *    ObjectInputStream(InputStream in)
    *
    * 注意:
    * 使用对象输出流写出对象,只能使用对象输入流来读取对象
    * 只能将支持 java.io.Serializable 接口的对象写入流中

    Demo

    public class O1_流对象概述 {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            writeMethod();
            //使用对象输出流写出对象,只能使用对象输入流来读取对象
            readMethod();
    
    
        }
    
        private static void readMethod() throws IOException, ClassNotFoundException {
            //创建输入流对象(读入数据)
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oo.txt"));
    
            //读取数据
            String s = (String)ois.readObject();
            System.out.println(s);
    
            int i = ois.readInt();
            System.out.println(i);
    
            Date d = (Date)ois.readObject();
            System.out.println(d);
    
            //释放资源
            ois.close();
        }
    
        //创建输出流对象(写出数据)
        private static void writeMethod() throws IOException {
            //创建输出流对象(写出数据)
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oo.txt"));
    
            //写数据
            oos.writeObject("hello");//写字符串对象
            oos.writeInt(123);
            oos.writeObject(new Date());//写日期对象
    
            //释放资源
            oos.close();
        }
    }

    输出:

    使用对象输出流写出对象,只能使用对象输入流来读取对象。写入的oo.txt文件用文本编辑器不能查看,只能用对象流查看。(序列化与反序列化)

  • 相关阅读:
    P3158 [CQOI2011]放棋子
    Codeforces 1220D. Alex and Julian
    Codeforces 1220C. Substring Game in the Lesson
    Codeforces 1220B. Multiplication Table
    BZOJ 3260. 跳
    BZOJ 3251. 树上三角形
    P1398 [NOI2013]书法家
    P1224 [NOI2013]向量内积
    The Preliminary Contest for ICPC Asia Shanghai 2019 A. Lightning Routing I
    P4271 [USACO18FEB]New Barns
  • 原文地址:https://www.cnblogs.com/longesang/p/11320118.html
Copyright © 2011-2022 走看看