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文件用文本编辑器不能查看,只能用对象流查看。(序列化与反序列化)

  • 相关阅读:
    HTML学习记录之HTML组成原理 PHP学习铺垫
    最长上升子序列(Longest increasing subsequence)
    进程保护(二)
    进程保护(一)
    屏幕广播的实现(三)
    vs2010 调试快捷键
    [整理]C#.Net的常见面试试题附答案(ZT)
    C# 中处理字符串常用的函数及方法详细说明
    Linux 系统下 /etc/group 档案结构
    C# Thread 多种写法总结
  • 原文地址:https://www.cnblogs.com/longesang/p/11320118.html
Copyright © 2011-2022 走看看