import java.io.*;
/** * Java对象的序列化测试 * File: ObjectStreamTest.java * User: leizhimin * Date: 2008-3-12 20:41:43 */ public class ObjectStreamTest {
public static void main(String args[]) {
testObjectSeri();
testObjectInSeri();
}
/** * 对象序列化测试 */ public static void testObjectSeri() {
Person person =
new Person(
"熔岩",
"341022225562156",
"lavasoft");
FileOutputStream fos =
null;
ObjectOutputStream oos =
null;
try {
fos =
new FileOutputStream(
"Q:\\study\\java5study\\src\\io\\person.dat");
oos =
new ObjectOutputStream(fos);
oos.writeObject(person);
}
catch (FileNotFoundException e) {
System.out.println(
"找不到指定的文件!");
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
oos.flush();
oos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/** * 对象反序列化测试 */ public static void testObjectInSeri() {
FileInputStream fis =
null;
ObjectInputStream ois =
null;
Person person =
null;
try {
fis =
new FileInputStream(
"Q:\\study\\java5study\\src\\io\\person.dat");
ois =
new ObjectInputStream(fis);
person = (Person) ois.readObject();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally {
try {
ois.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(person.toString());
}
}
/** * 测试序列化所用的类 */ class Person
implements Serializable {
private String username;
private String cardNumber;
private transient String password;
public Person(String username, String cardNumber, String password) {
this.username = username;
this.cardNumber = cardNumber;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
StringBuffer sb =
new StringBuffer(
this.getClass().getName());
sb.append(
"[");
sb.append(
"\n\t");
sb.append(
"username=" +
this.username);
sb.append(
"\n\t");
sb.append(
"cardNumber=" +
this.cardNumber);
sb.append(
"\n\t");
sb.append(
"password=" +
this.password);
sb.append(
"]");
return sb.toString();
}
}