注意的是,要保存的对象一定要实现了Serializable接口。
实现了Serializable接口对象才能被序列化。
//保存在本地
public void fileSave2Local(Object obj) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
//通过openFileOutput方法得到一个输出流
fos = openFileOutput("obj.out", Context.MODE_WORLD_READABLE);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj); //写入
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close(); //最后关闭输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
//保存在sd卡
public boolean fileSave2SDCard(Object obj) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File sdFile = new File(sdCardDir, "obj.out");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(sdFile);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj); //写入
oos.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) fos.close();
if (oos != null) oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
读取文件
public Object readFileFromLocal(String fileName) {
FileInputStream fileInputStream = null;
ObjectInputStream objectInputStream = null;
try {
fileInputStream = new FileInputStream(fileName + ".out");
objectInputStream = new ObjectInputStream(fileInputStream);
Object obj = objectInputStream.readObject();
return obj;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) fileInputStream.close();
if (objectInputStream != null) objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public Object readObjFromSDCard(String fileName) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Object obj;
File sdCardDir = Environment.getExternalStorageDirectory(); //获取SDCard目录
File sdFile = new File(sdCardDir, fileName + ".out");
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(sdFile); //获得输入流
ois = new ObjectInputStream(fis);
obj = ois.readObject();
return obj;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) fis.close();
if (ois != null) ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
作者:https://blog.csdn.net/qq_16628781
https://blog.csdn.net/qq_16628781/article/details/68957762