Trang chủ > Android > Serialize và Deserialize một object trong Android

Serialize và Deserialize một object trong Android


Đôi lúc ta muốn serialize một object cùng trạng thái các thuộc tính của nó tại một thời điểm nhất định xuống một file và deserialize object đó để lấy được các thuộc tính của object tại thời điểm mà nó được lưu xuống file. Trong Android ta làm như sau:

public void writeObjectToFile(Context context, MyObject myObj){
File file = new File(context.getDir("data", Context.MODE_PRIVATE),"fileName");
ObjectOutputStream outputStream;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(file));
outputStream.writeObject(myObj);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public MyObject readObjectFromFile(Context context, String fileName){
MyObject myObj = null;
File file = new File(context.getDir("data", Context.MODE_PRIVATE), fileName);
InputStream instream = null;
try {
instream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
myObj = (MyObject) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return myObj;
}

Chuyên mục:Android
  1. Không có bình luận
  1. No trackbacks yet.

Bình luận về bài viết này