android如何保存对象list到file

//存储
public static void saveObjectsToFile(List<? extends Serializable> objects, String filename) throws IOException {
File file1 = BaseApplication.getInstance()
.getApplicationContext().getExternalFilesDir("");
File appDir = new File(file1, filename);
if (!appDir.exists()) {
appDir.mkdirs();
}
String dataName =filename+".txt" ;
File file = new File(appDir, dataName);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(objects);
out.close();
}
//读取
@SuppressWarnings("unchecked")
public static List<MyObject> loadObjectsFromFile(String filename) throws IOException, ClassNotFoundException {
File file1 = BaseApplication.getInstance()
.getApplicationContext().getExternalFilesDir("");
File appDir = new File(file1, filename);
String dataName =filename+".txt" ;
File file = new File(appDir, dataName);
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
List<MyObject> objects = (List<MyObject>) in.readObject();
in.close();
return objects;
}
//序列化
public class MyObject implements Serializable {
}
posted @ 2024-06-04 10:06  only_books  阅读(8)  评论(0编辑  收藏  举报