一:序列化:Seralizable
二:序列化的控制:Externalizable
class Blip1 implements Externalizable{
public Blip1(){
System.out.println("blip1 contructor");
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
System.out.println("Blip1.read");
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("blip1.write");
}
}
class Blip2 implements Externalizable{
public Blip2(){
System.out.println("blip2 contructor");
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
System.out.println("Blip2.read");
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("blip2.write");
}
}
class Blip3 implements Externalizable{
int i;
String s;
public Blip3(){
System.out.println("blip3 contructor!");
}
public Blip3(int i,String s){
this.i=i;
this.s=s;
}
public String toString(){
return s+" "+i;
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
i=in.readInt();//这里很重要
s=(String) in.readObject();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(i);//这里很重要
out.writeObject(s);
}
}
public class Test{
static String str=new String("hello\nworld\nnihao\n");
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
// ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("s.out"));
// Blip1 b1=new Blip1();
// Blip2 b2=new Blip2();
// out.writeObject(b1);
// out.writeObject(b2);
// out.close();
// ObjectInputStream in=new ObjectInputStream(new FileInputStream("s.out"));
// b1=(Blip1)in.readObject();
// b2=(Blip2)in.readObject();
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("ss.out"));
Blip3 b3=new Blip3(23,"dz");
System.out.println(b3);
out.writeObject(b3);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream("ss.out"));
b3=(Blip3) in.readObject();
System.out.println(b3);
}
}
三:当用Seralizable尔不想对其中的密码序列化:transient(瞬时)关键字
class Blip4 implements Serializable{
private String name;
private transient String password;
public Blip4(String name,String password) {
this.name=name;
this.password=password;
}
public String toString(){
return name+" "+password;
}
}
下面得到的结果是:dz hel dz null
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("sss.out"));
Blip4 b4=new Blip4("dz","hel");
out.writeObject(b4);
System.out.println(b4);
ObjectInputStream in=new ObjectInputStream(new FileInputStream("sss.out"));
b4=(Blip4) in.readObject();
System.out.println(b4);