什么是序列化和反序列化
序列化 :把Java对象转换为字节码
反序列化:把字节码还原为Java对象
示例代码
import java.io.*;
class Users implements Serializable{
private String username;
private String password;
public Users(String username,String password){
this.username=username;
this.password=password;
}
public String getUsername(){
return this.username;
}
public String getPassword(){
return this.password;
}
public String toString(){
return "name="+this.username+" "+"password="+this.password;
}
}
public class ObjectWriteandRead{
public static String path="F:\\NotePadPP\\";
public static String ObjectFilename="users.txt";
public static void main(String[]args){
Users user=new Users("Tom","123");
try{
File file=new File(path+ObjectFilename);
file.createNewFile();
FileOutputStream fileoutputstream = new FileOutputStream(file);
ObjectOutputStream objectoutputstream = new ObjectOutputStream(fileoutputstream);
objectoutputstream.writeObject(user);
objectoutputstream.flush();
objectoutputstream.close();
fileoutputstream.close();
FileInputStream fileinputstream = new FileInputStream(file);
ObjectInputStream objectinputstream = new ObjectInputStream(fileinputstream);
Users userinput = (Users) objectinputstream.readObject();
objectinputstream.close();
fileinputstream.close();
System.out.println(userinput.toString());
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
输出结果:
使用序列化和反序列化实现单例模式
import java.io.*;
class MyOject implements Serializable{
private static class MyOjectHandler{
private static MyOject myObject=new MyOject();
}
private MyOject(){}
public static MyOject getInstance(){
return MyOjectHandler.myObject;
}
protected Object readResolve()throws ObjectStreamException{
return MyOjectHandler.myObject;
}
}
public class ObjectWriteandRead{
public static String path="F:\\NotePadPP\\";
public static String ObjectFilename="object.txt";
public static void main(String[]args){
MyOject myObject=MyOject.getInstance();
try{
File file=new File(path+ObjectFilename);
file.createNewFile();
FileOutputStream fileoutputstream = new FileOutputStream(file);
ObjectOutputStream objectoutputstream = new ObjectOutputStream(fileoutputstream);
objectoutputstream.writeObject(myObject);
objectoutputstream.flush();
objectoutputstream.close();
fileoutputstream.close();
System.out.println(myObject.hashCode());
FileInputStream fileinputstream = new FileInputStream(file);
ObjectInputStream objectinputstream = new ObjectInputStream(fileinputstream);
MyOject myObjectinput = (MyOject) objectinputstream.readObject();
objectinputstream.close();
fileinputstream.close();
System.out.println(myObjectinput.hashCode());
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
输出结果:
关键代码:
protected Object readResolve()throws ObjectStreamException{
return MyOjectHandler.myObject;
}
如果不在MyObject中调用写这段代码就不会得到单例。