标签:
好久没翻译simple java了,睡前来一发。译文链接:http://www.programcreek.com/2014/01/java-serialization/
在Java中,对象序列化指的是将对象用字节序列的形式表示,这些字节序列包含了对象的数据和信息,一个序列化后的对象可以被写到数据库或文件中,并且支持从数据库或文件中反序列化,从而在内存中重建对象;
序列化经常被用于对象的网络传输或本地存储。网络基础设施和硬盘只能识别位和字节信息,而不能识别Java对象。通过序列化能将Java对象转成字节形式,从而在网络上传输或存储在硬盘。
那么为什么我们需要存储或传输对象呢?根据我的编程经验,有如下原因需要将对象序列化(以下原因,我表示没使用过。。。):
顺便也说下,根据我(真正的我)的编程经验,序列化使用情况如下:
以下代码展示了如何让一个类可序列化,对象的序列化以及反序列化;
对象:
package serialization; import java.io.Serializable; public class Dog implements Serializable { private static final long serialVersionUID = -5742822984616863149L; private String name; private String color; private transient int weight; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public void introduce() { System.out.println("I have a " + color + " " + name + "."); } }
main方法
package serialization; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializeDemo { public static void main(String[] args) { // create an object Dog e = new Dog(); e.setName("bulldog"); e.setColor("white"); e.setWeight(5); // serialize try { FileOutputStream fileOut = new FileOutputStream("./dog.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized dog is saved in ./dog.ser"); } catch (IOException i) { i.printStackTrace(); } e = null; // Deserialize try { FileInputStream fileIn = new FileInputStream("./dog.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Dog) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Dog class not found"); c.printStackTrace(); return; } System.out.println("\nDeserialized Dog ..."); System.out.println("Name: " + e.getName()); System.out.println("Color: " + e.getColor()); System.out.println("Weight: " + e.getWeight()); e.introduce(); } }
结果打印:
标签:
原文地址:http://www.cnblogs.com/chenpi/p/5582492.html