將對象寫入到流,這個過程叫做序列化。
反之,稱為反序列化。
如果要用于網絡中傳輸?shù)臄?shù)據(jù),則這些數(shù)據(jù)必須要實現(xiàn)序列化。
例1:
// Student.java
package test;
public class Student {
String name;
int age;
String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void study() {
System.out.println("我在認真學習");
}
@Override
public String toString() {
return "我的名字:" + name + ",我的年齡:"
+ age + ",我的性別:" + sex;
}
}
// Test.java
package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class Test {
public static void main(String[] args) {
Student stu = new Student("李行之", 25, "男");
File file = new File("a.txt");
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(stu);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

運行結果,未進行序列化,因此無法將對象寫入流中。13行:oos.writeObject(stu);
例2:
// 1. Student.java
package test;
import java.io.Serializable;
/*
* implements Serializable:實現(xiàn)序列化接口。
* 它沒有任何方法需要實現(xiàn),只是一個標識。
* 序列化之后,會有一個編號植入到對象中;當寫入到磁盤時,會將編號一起寫入磁盤。
*/
public class Student implements Serializable{
String name;
int age;
String sex;
// transient:不序列化某些屬性
transient long money = 10000000;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void study() {
System.out.println("我在認真學習");
}
@Override
public String toString() {
return "我的名字:" + name + ",我的年齡:"
+ age + ",我的性別:" + sex + ",我的錢:" + money;
}
}
// 2. Test.java
package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/**
* 序列化
* @author xiangdonglee
*
*/
public class Test {
public static void main(String[] args) {
Student stu = new Student("李行之", 25, "男");
File file = new File("a.txt");
if(!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(stu);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

序列化結果
// 3.Test1.java
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* 反序列化
* @author xiangdonglee
*
*/
public class Test1 {
public static void main(String[] args) {
File file = new File("a.txt");
if(file.exists()) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Student stu = (Student) ois.readObject();
System.out.println(stu);
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

transient修飾的money屬性沒有被序列化