这篇是一个Serializable的一个例子。Android 主要用 Serializable 和 Parcelable 来实现对象的序列化。
需要说明的是如果Person 是内部类,需要加上Static 属性;不然会提示 Person没有序列化。
同时因为 Serializable 接口使得类不容易维护。可以参看 Effect java 相关章节。
package com.serializabletest;
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.io.Serializable;
import java.io.StreamCorruptedException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
public static final String TAG = "MainActivity";
/** 序列化测试
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
private final String objName = "/mnt/sdcard/object.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("通过实现 Serializable 接口来实现对象序列化");
setContentView(R.layout.activity_main);
}
public void writePerson(View view) throws FileNotFoundException,
IOException {
Person person = new Person(1, "张三", 20);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
objName));
oos.writeObject(person);
oos.flush();
oos.close();
person.printPerson();
}
public void readPerson(View view) throws StreamCorruptedException,
FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
objName));
Person person = (Person) ois.readObject();
ois.close();
person.printPerson();
}
static class Person implements Serializable {
private static final long serialVersionUID = 1L;
int ID;
String Name;
int age;
public Person(int ID, String Name, int age) {
this.ID = ID;
this.Name = Name;
this.age = age;
}
public void printPerson() {
Log.d(TAG, "ID:" + ID);
Log.d(TAG, "Name:" + Name);
Log.d(TAG, "age:" + age);
}
}
}