Java Serializable

  2016-12-22  代码片段编程技术   4 分钟

概述

  • Java序列化就是把对象转换成字节序列,而Java反序列化就是把字节序列还原成Java对象。

  • 采用Java序列化与反序列化技术,一是可以实现数据的持久化,二是可以对象数据的远程通信

package com.infullstack.learning.Serializable;

import java.io.*;

/**
 * Created by Ray on 2016/12/22 0022.
 */
public class TestSerializable {

    public static void main(String[] args) {
        Student st = new Student("Tom", 'M', 20, 3.6);
        File file = new File("D:\\infullstack\\learning\\serializable\\student.txt");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //Student对象序列化过程
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(st);
            oos.flush();
            oos.close();
            fos.close();

            //Student对象反序列化过程
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Student st1 = (Student) ois.readObject();
            System.out.println("name = " + st1.getName());
            System.out.println("sex = " + st1.getSex());
            System.out.println("year = " + st1.getYear());
            System.out.println("gpa = " + st1.getGpa());
            ois.close();
            fis.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Student implements Serializable {
    private String name;
    private char sex;
    private int year;
    private double gpa;

    public Student() {

    }

    public Student(String name, char sex, int year, double gpa) {
        this.name = name;
        this.sex = sex;
        this.year = year;
        this.gpa = gpa;
    }

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

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

    public void setYear(int year) {
        this.year = year;
    }

    public void setGpa(double gpa) {
        this.gpa = gpa;
    }

    public String getName() {
        return this.name;
    }

    public char getSex() {
        return this.sex;
    }

    public int getYear() {
        return this.year;
    }

    public double getGpa() {
        return this.gpa;
    }
}

— 转载本站文章请注明作者和出处全栈记 ,请勿用于任何商业用途

— 于 2016年12月22日 ,共写了 1574 字;

— 本文共有 1 个标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注