SerializableDemo 一个java序列化的例子

序列化在很多地方都会用到,可以传输对象。下面是一个简单的本地存储的序列化例子。
代码:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableDemo {
public static void main(String[] args) throws Exception{
new Bak(“11231231”,”as5d45asd”,1,0).backup();
Bak bak = Bak.recover();

    System.out.println(bak.account);
    System.out.println(bak.password);
    System.out.println(bak.remPassword);
    System.out.println(bak.autoLogin);
}

}

class Bak implements Serializable {
/**

 * 
 */
private static final long serialVersionUID = 1L;
public String account;
public String password;
public int remPassword;
public int autoLogin;
Bak(String account,String password,int remPassword,int autoLogin) {
    this.account = account;
    this.password = password;
    this.remPassword = remPassword;
    this.autoLogin = autoLogin;
}
public void backup () throws Exception{
    File file = new File("C:"+File.separator+"WINDOWS"+File.separator+"qsuron.bak");
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
    oos.writeObject(this);
    oos.close();
}
public static Bak recover () throws Exception{
    File file = new File("C:"+File.separator+"WINDOWS"+File.separator+"qsuron.bak");
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
    Bak bak = (Bak)ois.readObject();
    ois.close();
    return bak;
}

}


例子输出:


11231231

as5d45asd

1

0

0%