码迷,mamicode.com
首页 > 其他好文 > 详细

对象序列化

时间:2019-04-05 19:36:22      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:void   str   over   cat   string   otf   getname   tag   tac   

1.对象

import java.io.Serializable;

public class Dog implements Serializable {

    private String name;
    private int age;
    private String sex;

    public Dog(String name, int age, String sex) {

        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ", sex=‘" + sex + ‘\‘‘ +
                ‘}‘;
    }
}

2.对象序列化

import java.io.*;

public class file {

    public static void main(String[] args) throws FileNotFoundException {
        in();
    }
    private static void in(){
        Dog dog = new Dog("11",2,"男");
        File file = new File("F:/学习/1.txt");
        try {
            OutputStream outputStream = new FileOutputStream(file);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(dog);
            objectOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 3.对象反序列化

import java.io.*;

public class file {

    public static void main(String[] args) throws FileNotFoundException {
        out();
    }
    private static void out(){
        File file = new File("F:/学习/1.txt");
        try {
            InputStream inputStream = new FileInputStream(file);
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            Dog dog = (Dog)objectInputStream.readObject();
            System.out.println(dog);
            objectInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

 

对象序列化

标签:void   str   over   cat   string   otf   getname   tag   tac   

原文地址:https://www.cnblogs.com/mm163/p/10659566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!