Java Serialization of Java Objects and Primitives
一、Introduction
1. What is Java Serialization?
Java Serialization is the process of converting the state information of JavaTM objects into a form(byte stream) that can be stored or transmitted.
Java Serialization is used to store and retrieve JavaTM objects, which is essential to building the most applications.
2. Why we need Java Serialization?
objects persistence、transmission and extensible mechanism
二、Simples
1 public class SerializationTest { 2 3 public static void main(String[] args) { 4 try { 5 // FileOutputSteam is used to receive bytes 6 FileOutputStream fos = new FileOutputStream("tmp"); 7 // ObjectOutput serializes Array, enum constants, Class Object, String 8 ObjectOutput objectOutput = new ObjectOutputStream(fos); 9 // DataOutputStream serializes primitive data, such as int, char, byte, boolean 10 DataOutputStream dos = new DataOutputStream(fos); 11 12 objectOutput.writeObject("hello serialization"); 13 objectOutput.flush(); 14 15 dos.writeBoolean(true); 16 dos.flush(); 17 18 // Reading an object from a stream 19 FileInputStream fis = new FileInputStream("tmp"); 20 ObjectInputStream ois = new ObjectInputStream(fis); 21 DataInputStream dis = new DataInputStream(fis); 22 23 String s = (String)ois.readObject(); 24 boolean b = dis.readBoolean(); 25 26 System.out.println(s); // hello serialization 27 System.out.println(b); // true 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } 31 } 32 }