上一篇文章中介绍了如何将对象保存在本地,这篇文章主要介绍如何将对象保存在SD卡中:
有了上一篇文章的基础,这里我只用介绍两个方法就OK了。
1. 将对象写入SD卡中
<span style="white-space:pre"> </span>/**
* @function 将一个对象保存到SD卡中
* @author D-light
* @time 2014-07-23
* @param String name
* @return void
*/
private void saveObject2SD(String path){
FileOutputStream fos = null;
ObjectOutputStream oos = null;
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, path);
try {
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(sod);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<span style="white-space:pre"> </span>/**
* @function 从SD卡中读取保存的对象
* @author D-light
* @time 2014-07-23
* @param String name
* @return Object
*/
private Object getObjectFromSD(String path){
FileInputStream fis = null;
ObjectInputStream ois = null;
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, path);
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
根据上一篇文章的介绍,其实不难得到我们的结果:
还要加上权限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>