学习了一下Java对象的序列化与反序列化,下面的代码是一个简单的例子。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
public class sirializableTest implements Serializable
{
private String username;
private transient String password; //不会参与序列化与反序列化的过程
public sirializableTest(String username, String password)
{
this.username = username;
this.password = password;
}
public String toString()
{
return "username: " + username + ", password: " + password;
}
public static void main(String[] args)
{
try
{
File f = new File("C:\\a.obj");
if(!f.exists())
f.createNewFile();
//序列化对象
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject("Happy New Year !");
out.writeObject(new Date());
sirializableTest test = new sirializableTest("yoyo", "20090105");
out.writeObject(test);
out.close();
//反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
System.out.println(in.readObject()); //输出:Happy New Year !
System.out.println(in.readObject()); //输出:Mon Jan 05 17:18:39 CST 2009
System.out.println(in.readObject()); //输出:username: yoyo, password: null
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
}
当然,保存的文件也可以是其他格式。如果用记事本打开,会看到一堆乱码。