Java 序列化与反序列化 —— 序列化为一般二进制格式文件
2014-06-24 13:44
1006 查看
Step1:创建一个实现了Serializable接口的类
Step2:通过ObjectOutputStream对象序列化保存数据
Step3:通过ObjectInputStream对象反序列化数据为实例对象
import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 172447632608611914L; private String name; private int age; public Person() { } public Person(String name, int age) { System.out.println("Inside Person's Constructor"); this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
Step2:通过ObjectOutputStream对象序列化保存数据
import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class WritePerson { public static void main(String[] args) throws IOException { FileOutputStream outFile = null; ObjectOutputStream out = null; try { String path = "src/myPerson.bin"; outFile = new FileOutputStream(path); out = new ObjectOutputStream(outFile); Person person = new Person("张三", 20); out.writeObject(person); System.out.println("序列化对象成功"); } catch (Exception e) { e.printStackTrace(); } finally { if (outFile != null) outFile.close(); if (out != null) out.close(); } } }
Step3:通过ObjectInputStream对象反序列化数据为实例对象
import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class ReadPerson { public static void main(String[] args) throws IOException, ClassNotFoundException { String path = "src/myPerson.bin"; FileInputStream fileIn = null; ObjectInputStream in = null; try { fileIn = new FileInputStream(path); in = new ObjectInputStream(fileIn); Person person = (Person) in.readObject(); if (person != null) { System.out.println(person); } else { System.out.println("反序列化对象失败"); } } catch (Exception e) { e.printStackTrace(); } finally { if (fileIn != null) fileIn.close(); if (in != null) in.close(); } } }
相关文章推荐
- Java 二进制格式文件转换为doc文件并保存在指定路径下
- 通过阅读、分析和翻译二进制格式的Java Class文件学习Java Class的技术
- C++ 内存数据结构与二进制文件之间的序列化和反序列化
- Java 对象直接写入文件 --序列化和反序列化
- Java中List或者HashMap对象-序列化和反序列化并附读写文件操作
- XStream java对象和json文件进行序列化和反序列化
- IDEA-->JAVA 一般文件格式转PDF格式
- Java二进制Class文件格式解析
- DataTable的序列化和反序列化(格式不变保存文件和读取)
- [Java学习] 将PDF格式文件转成二进制并生成Base64编码,将Base64编码转成PDF文件
- java序列化,反序列化及反序列如何判断是否已读到文件末尾
- java中的序列化与反序列化,还包括将多个对象序列化到一个文件中
- Java序列化 - 二进制格式详解
- Java 序列化反序列化文件
- Java,C#使用二进制序列化、反序列化操作数据
- 文章标题 Java中io流的一些简单操作(包含文件复制,向硬盘中写入文本文件,以及io流高级应用序列化和反序列化)
- Java序列化和反序列化超强工具类(包含tif图片与其他格式互转)
- java中对象和json格式相互序列化和反序列化的函数
- 如何用JAVA将二进制文件转换成BASE64格式保存到MySQL的Blob字段里并读出下载
- Java二进制Class文件格式解析