序列化
序列化:将对象转换为二进制序列在网络中传输或保存到磁盘
反序列化:从网络或磁盘中将二进制序列转换为对象
注意:
对象必须实现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序列化和反序列化内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!
黄山市民网:https://www.huangshanshimin.com/