下面内容段是关于Java对对象的序列化和反序列化的内容,应该是对各位朋友有些用。
package com.bird.thinking;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Data {
public static void writeObject() throws Exception{
Worm worm = new Worm("Bird");
out.writeObject(worm);
}
public static void readObject() throws Exception{
Worm s2 = (Worm) in.readObject();
System.out.println(s2);
}
public static void main(String[] args) throws Exception{
readObject();
}
}
class Worm implements Serializable{
private static final long serialVersionUID = 1L;
private String name = null;
public Worm(String name){
this.name = name;
}
public String toString(){
return name;
}
}
下面这是第二种方式
package com.bird.thinking;
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class Blip3 implements Externalizable {
private int i;
public Blip3(){
System.out.println("Blip3 Constructor!!");
}
public Blip3(String x, int a){
System.out.println("Blip3(String x, int a)");
s = x;
i = a;
}
public String toString(){
return s + i;
}
System.out.println("Blip3.writeExternal");
try {
out.writeObject(s);
out.writeInt(i);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Blip3.readExternal");
try {
s = (String)in.readObject();
i = in.readInt();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
throw new RuntimeException(e);
}
}
System.out.println("Revovering b3");
Blip3 b3 = (Blip3)in.readObject();
System.out.println(b3);
}
Blip3 b3 = new Blip3("A String", 47);
System.out.println(b3);
System.out.println("Saving Object");
o.writeObject(b3);
o.close();
}
public static void main(String[] args) throws Exception{
Blip3 b = new Blip3();
b.read();
}
}
输出结果
Blip3 Constructor!!
Blip3(String x, int a)
A String47
Saving Object
Blip3.writeExternal
输出结果
Blip3 Constructor!!
Revovering b3
Blip3 Constructor!!
Blip3.readExternal
A String47