【问题标题】:How to write an ArrayList to file and retrieve it?如何将 ArrayList 写入文件并检索它?
【发布时间】:2012-08-28 11:39:12
【问题描述】:

现在我正在尝试使用它

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

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

提前致谢

【问题讨论】:

  • 返回使用 ObjectInputStream().readObject();并检查 ArrayList 的实例

标签: android


【解决方案1】:

这是你想做的吗?

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() 方法。

【讨论】:

    【解决方案2】:

    使用此方法将您的 Arraylist 写入文件

    public static void write(Context context, Object nameOfClass) {
        File directory = new File(context.getFilesDir().getAbsolutePath()
                + File.separator + "serlization");
        if (!directory.exists()) {
            directory.mkdirs();
        }
    
        String filename = "MessgeScreenList.srl";
        ObjectOutput out = null;
    
        try {
            out = new ObjectOutputStream(new FileOutputStream(directory
                    + File.separator + filename));
            out.writeObject(nameOfClass);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    Complete example here, with Read method

    【讨论】:

    • 上述链接失效!你能更新你的评论吗?
    猜你喜欢
    • 2020-01-28
    • 1970-01-01
    • 2016-05-05
    • 2018-08-09
    • 2019-05-08
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多