zoukankan      html  css  js  c++  java
  • [Java 12 IO] Serializable 初步 ObjectOutputStream ObjectInputStream 将序列化的对象打出来

    Person 类, 序列化后就代表对象可以作为二进制的数据流进行传输
    package com.qunar.basicJava.javase.io.serializable;
    
    import java.io.Serializable;
    
    /**
     * Author: libin.chen@qunar.com  Date: 14-6-6 10:21
     */
    public class Person implements Serializable {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "姓名 : " + this.name + "; 年龄 : " + this.age;
    
        }
    }
    
    ObjectOutputStream 将序列化后的对象写入到文件中
    package com.qunar.basicJava.javase.io.serializable;
    
    import java.io.*;
    
    /**
     * Author: libin.chen@qunar.com  Date: 14-6-6 10:25
     */
    public class SerDemo01 {
        public static void main(String[] args) throws IOException {
            File file = new File("/home/hp/tmp/test.txt");
            ObjectOutputStream objectOutputStream = null;
            OutputStream outputStream = new FileOutputStream(file);
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(new Person("张三", 30));
            outputStream.close();
    
        }
    }
    
     ObjectInputStream 将序列化的对象传回来
    package com.qunar.basicJava.javase.io.serializable;
    
    import java.io.*;
    
    /**
     * Author: libin.chen@qunar.com  Date: 14-6-6 10:27
     */
    public class SerDemo02 {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            File file = new File("/home/hp/tmp/test.txt");
            ObjectInputStream objectInputStream = null;
            InputStream inputStream = new FileInputStream(file);
            objectInputStream = new ObjectInputStream(inputStream);
            Object object = objectInputStream.readObject();
            objectInputStream.close();
            System.out.println(object);
    
        }
    }
    


  • 相关阅读:
    java笔试面试题目收集(一)
    java--用 * 打印出各种图形(新手请进)
    TextView属性大赏
    Meterial Or Ios ?
    android开发之后端云bmob的使用
    关于android开发自定义view
    第二周作业——面向过程(或者叫结构化)分析方法与面向对象分析方法到底区别在哪里?
    移动APP开发使用什么样的原型设计工具比较合适?
    测试
    转:nohup命令及其输出文件
  • 原文地址:https://www.cnblogs.com/robbychan/p/3786488.html
Copyright © 2011-2022 走看看