1. 程式人生 > >Android Serialization序列化

Android Serialization序列化

Android Serialization

目的:

為了方便測試感測器資料處理演算法,Android程式的採集資料,序列化儲存為檔案;pc程式再通過反序列化讀入物件,在PC上測試演算法。

Java 序列化:

Java物件序列化為二進位制檔案的Java序列化技術是Java系列技術中一個較為重要的技術點,在大部分情況下,開發人員只需要瞭解被序列化的類需要實現Serializable介面,使用ObjectInputStreamObjectOutputStream進行物件的讀寫。

注意事項:

要序列化的物件的類要滿足以下條件:

1.類要實現Serializable

介面

2. serialize deserialize程式要保證package一致

3.serialVersionUID要一致


例程:

package com.example.coolwaterld.serializedemo;
import java.io.Serializable;
class Person implements Serializable //Added implements Serializable
{
    String name="";
    private String number="";
    private String address="";
    private static final long serialVersionUID = 1L;
       public String getName()
    {
        return name;
    }
    public String getNumber()
    {
        return number;
    }
    public String getAddress()
    {
        return address;
    }
}


package com.example.coolwaterld.serializedemo;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Person person = new Person();
        person.setName("coolwaterld");
        person.setAddress("BJ");
        person.setNumber("123");
        //save the object
        saveObject(person);
        // Get the Object
        Person person1 = (Person)loadSerializedObject(new File("/sdcard/person.bin")); 
        Log.i("Name", person1.getName());
    }
    public void saveObject(Person p){
        try
        {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/sdcard/kvmatrix.bin"))); 
            oos.writeObject(p); 
            oos.flush(); 
            oos.close();
        }
        catch(Exception  ex)
        {
            Log.v("Serialize write: ", ex.getMessage());
            ex.printStackTrace();
        }
    }
    public Object loadSerializedObject(File f)
    {
        try
        {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
            Object o = ois.readObject();
            return o;
        }
        catch(Exception ex)
        {
            Log.v("Serialize Read: ",ex.getMessage());
            ex.printStackTrace();
        }
        return null;
    }
}

在AndroidManifest.xml中
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


參考:

Java –Serialization

http://www.tutorialspoint.com/java/java_serialization.htm

Java 序列化的高階認識

http://www.ibm.com/developerworks/cn/java/j-lo-serial/index.html?ca=drs-#icomments

(序列化ID的問題,靜態變數序列化,父類的序列化與Transient關鍵字,對敏感欄位加密,序列化儲存規則)