Android Serialization
目的:
为了方便測试传感器数据处理算法,Android程序的採集数据。序列化保存为文件。pc程序再通过反序列化读入对象,在PC上測试算法。
Java 序列化:
将Java对象序列化为二进制文件的Java序列化技术是Java系列技术中一个较为重要的技术点,在大部分情况下,开发者仅仅须要了解被序列化的类须要实现Serializable接口。使用ObjectInputStream和ObjectOutputStream进行对象的读写。
注意事项:
要序列化的对象的类要满足下面条件:
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的问题,静态变量序列化,父类的序列化与Transientkeyword,对敏感字段加密,序列化存储规则)