首页 / JAVA / Java序列化的一个例子
Java序列化的一个例子
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java序列化的一个例子,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1407字,纯文字阅读大概需要3分钟。
内容图文
学习Java这么久,虽然脑子中有关于序列化的理解,但没实际应用过,刚好碰到朋友要帮忙做个作业,就趁机写一个很简单的例子。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * 对象的序列化主要有两种用途: 1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中; 2) 在网络上传送对象的字节序列。 */ /** * 要使对象序列化,就令该对象继承java.io.Serializable类。 */ /** * @author Jim * @Time 2016年4月14日 下午1:47:48 * */ public class Program21 { public static void main(String[] args){ try{ //序列化对象,将对象保存在student.dat中 ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.dat")); Student s1 = new Student("Lisa", 20); out.writeObject(s1); //写入对象 out.close(); //将student.dat中的对象反序列化并print information. ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.dat")); Student s2 = (Student)in.readObject(); //读出对象 System.out.print("Student‘s name is " + s2.getName() + " and the age is " + s2.getAge()); in.close(); }catch(Exception e){ e.printStackTrace(); } } } /** * 定义一个学生类来继承java.io.Serializable */ class Student implements Serializable { private String name = ""; private int age = 0; public Student(String name, int age) { this.name = name; this.age = age; } public String getName(){ return this.name; } public int getAge() { return this.age; } }
本文出自 “A&D_Ro535” 博客,请务必保留此出处http://ro535.blog.51cto.com/11279790/1763771
原文:http://ro535.blog.51cto.com/11279790/1763771
内容总结
以上是互联网集市为您收集整理的Java序列化的一个例子全部内容,希望文章能够帮你解决Java序列化的一个例子所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。