类的序列化和反序列化
来源:互联网 发布:unity3d虚拟现实源码 编辑:程序博客网 时间:2024/05/21 22:23
要使一个类能进行序列化操作,并实现Serializable接口
如果类中的某些成员变量不想实现序列化,则需要在前面添加关键字transient
实体类
package cn.io;import java.io.Serializable;/** * @author Duoduo * @version 1.0 * @date 2017/4/16 22:43 */public class Employee implements Serializable { private transient String name;// 不需要序列化 private double salary; public Employee(String name, double salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; }}
测试类
package cn.io;import java.io.*;/** * 只有类实现了 Serializable 才能进行序列化操作 * @author Duoduo * @version 1.0 * @date 2017/4/16 22:43 */public class Test3 { public static void main(String[] args) { writeObject(); readObject(); } /** * 反序列化 */ public static void readObject(){ File file = new File("/Users/Pengjinjin/Desktop/employee.txt"); ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))); Object object = objectInputStream.readObject(); if( object instanceof Employee){ Employee employee =(Employee)object; System.out.println(employee.getSalary()); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if(objectInputStream!=null){ try { objectInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 序列化 */ public static void writeObject() { File file = new File("/Users/Pengjinjin/Desktop/employee.txt"); ObjectOutputStream objectOutputStream = null; try { objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file))); Employee employee = new Employee("employee",1000); objectOutputStream.writeObject(employee); objectOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); }finally { if(objectOutputStream!=null){ try { objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
最后运行结果:获取到Employee的salary 为 1000
0 0
- 序列和反序列化
- 序列和反序列化
- 序列化和反序列化的工具类
- 类的序列化和反序列化
- 类的序列化和反序列化
- 对象的序列化和反序列化工具类
- JSON和plist的序列化和反序列化
- java 的序列化和反序列化的问题
- jackson的序列化和反序列化的实现
- 序列化和反序列化的概念 JDK类库中的序列化API serialVersionUID
- 序列化和反序列化
- 序列化和反序列化
- 序列化和反序列化
- c# 序列化和反序列化
- .NET序列化和反序列化
- .net序列化和反序列化
- 序列化和反序列化
- C#序列化和反序列化
- 白话空间统计二十三:回归分析番外-ArcGIS中的OLS(二)
- Session
- ubuntu-opencv自动安装脚本
- phpmyadmin管理数据库时的权限问题
- SQL基础语句
- 类的序列化和反序列化
- ubuntu16.04安装anaconda(阿里云下)
- MyBatis标签
- [2017.4.16]IMWEB前端小白训练营日记(二)
- 如何生成[0, N)中的随机数
- java设计模式--单例模式
- SSL2654 糊涂的教授
- Lintcode 验证二叉查找树
- android studio library 模块中正确引用aar