android - 如何将 ArrayList 写入文件并检索它?

标签 android

现在我正在尝试使用它

FileOutputStream fos = getContext().openFileOutput("CalEvents", Context.MODE_PRIVATE);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(returnlist);
    oos.close();

为了将 ArrayList 的“returnlist”保存到文件“CalEvents” 现在我的问题是,这是正确的方法吗? 以及如何取回列表?

提前致谢

最佳答案

这是你想做的吗?

FileInputStream fis;
try {
    fis = openFileInput("CalEvents");
    ObjectInputStream ois = new ObjectInputStream(fis);
    ArrayList<Object> returnlist = (ArrayList<Object>) ois.readObject();
    ois.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

编辑:可以简化:

FileInputStream fis;
try {
    fis = openFileInput("CalEvents");
    ObjectInputStream ois = new ObjectInputStream(fis);
    ArrayList<Object> returnlist = (ArrayList<Object>) ois.readObject();
    ois.close();
} catch (Exception e) {
    e.printStackTrace();
}

假设您所在的类扩展了 Context(如 Activity)。如果不是,那么您将必须在扩展 Context 的对象上调用 openFileInput() 方法。

关于android - 如何将 ArrayList 写入文件并检索它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12158483/

相关文章:

java - 将逗号分隔的字符串拆分为多个新字符串

android - 无法滚动 ListView

java - Android:EditText 的默认文本大小是多少?

java - 如何协调抽屉式导航与底部导航 View

android - 查看 Xml 的图形布局时 Eclipse 中的 XML 错误

android - 如何在Android应用程序中一起播放视频和音频

互联网上的 Android P2P(直接连接)(在 NAT 之后)

android - 键盘将 EditText 隐藏在 android 中的 ScrollView 中?

Android MPchart饼图图例设置自定义错误

android - 从 Android 股票浏览器中的网页打开 PDF