如何写一个ArrayList到文件并检索它? [英] How to write an ArrayList to file and retrieve it?

查看:131
本文介绍了如何写一个ArrayList到文件并检索它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我试着去使用这个

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

为了拯救returnlist,这是一个ArrayList到文件CalEvents 现在我的问题是,这是正确的方式做到这一点? 我如何检索列表回来?

in order to save "returnlist" which is an ArrayList to the file "CalEvents" now my question is , is that the right way to do it? and how do i retrieve the list back?

在此先感谢

推荐答案

这是你想要做什么?

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();
}

假设你是在一个类延伸上下文(如活动)。如果没有,那么你将不得不调用 openFileInput()方法的对象延伸的上下文

Assuming that you are in a class which extends Context (like Activity). If not, then you will have to call the openFileInput() method on an object which extends Context.

这篇关于如何写一个ArrayList到文件并检索它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆