序列化:将对象转换为二进制序列在网络中传输或保存到磁盘
反序列化:从网络或磁盘中将二进制序列转换为对象
注意:
对象必须实现Serializable接口
对象的所有属性都要能序列化(Integer,Byte等都进行了序列化)
String
Integer
1.编写大象类
public class Elephant implements Serializable { private String name; private String age; private String sex; public Elephant(String name, String age, String sex) { this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Elephant{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", sex='" + sex + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
2.大象测试类
public class ElephantTest { public static final String PATH = "D:\\elephant"; static void write(Elephant elephant){ //创建对象输出流 try( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) { //写入对象 out.writeObject(elephant); } catch (IOException e) { e.printStackTrace(); } } static Object read(){ //创建对象输出流 try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) { //写入对象 return in.readObject(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { Elephant elephant7 = new Elephant("小红象", "18", "男"); write(elephant7); Elephant elephant1 = (Elephant) read(); System.out.println(elephant1); System.out.println(elephant7); System.out.println(elephant1==elephant7); } }
运行结果:
写入D盘的对象:
到此这篇关于Java序列化和反序列化的文章就介绍到这了,更多相关Java序列化和反序列化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
免责声明:本站发布的内容(图片、视频和文字)以原创、来自互联网转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系QQ:712375056 进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
Copyright © 2009-2021 56dr.com. All Rights Reserved. 特网科技 特网云 版权所有 珠海市特网科技有限公司 粤ICP备16109289号
域名注册服务机构:阿里云计算有限公司(万网) 域名服务机构:烟台帝思普网络科技有限公司(DNSPod) CDN服务:阿里云计算有限公司 中国互联网举报中心 增值电信业务经营许可证B2
建议您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流浏览器浏览本网站