码迷,mamicode.com
首页 > 编程语言 > 详细

learning java 实例序列化

时间:2019-08-05 17:21:56      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:obj   方法   input   set   style   puts   try   color   cat   

对Person类实例进行序例化及反序例化:

Person.java

public class Person
    implements java.io.Serializable
{
    private String name;
    private int age;
    // 注意此处没有提供无参数的构造器!
    public Person(String name, int age)
    {
        System.out.println("有参数的构造器");
        this.name = name;
        this.age = age;
    }
    // 省略name与age的setter和getter方法

    // name的setter和getter方法
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return this.name;
    }

    // age的setter和getter方法
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getAge()
    {
        return this.age;
    }
}

WriteObject:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class WriteObject {
    public static void main(String[] args) {
        try {
            var oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
            var per = new Person("孙武空",500);
            oos.writeObject(per);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ReadObject:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ReadObject {
    public static void main(String[] args) throws FileNotFoundException {
        try {
            var ois = new ObjectInputStream(new FileInputStream("object.txt"));
            var p = (Person)ois.readObject();
            System.out.println("name: " + p.getName() + " age : " + p.getAge());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

 

learning java 实例序列化

标签:obj   方法   input   set   style   puts   try   color   cat   

原文地址:https://www.cnblogs.com/lianghong881018/p/11304036.html

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