【问题标题】:android storing an arraylist of serialized objects in a fileandroid在文件中存储序列化对象的arraylist
【发布时间】:2023-03-27 15:46:01
【问题描述】:

我想将对象的数组列表存储在一个文件中,以便在再次打开应用程序后访问它们。

public class SmsMessage implements Serializable {

    public static enum MessageType {
        Sent,
        Received;
    };

    private String body;
    private Date date;
    private MessageType type;

    public SmsMessage(String _body, Date _date, MessageType _type) {
        body = _body;
        date = _date;
        type = _type;

    }

}

这就是整个班级。我是这样保存的:

FileOutputStream fout = null;
ObjectOutputStream out = null;
    try {
        fout = context.getApplicationContext()
                    .openFileOutput(FILENAME, Context.MODE_PRIVATE);
        out = new ObjectOutputStream(fout);
        out.writeObject(list);
        out.close();

    } catch (IOException ioe) {
        System.out.println("Error in save method");

    } finally {
        out.close();
        fout.close();
}

然后这样读:

ObjectInputStream in = null;
FileInputStream fis = null;
    try {
        fis = context.getApplicationContext().openFileInput(FILENAME);
        in = new ObjectInputStream(fis);
        ArrayList<SmsMessage> list = null;
        list = (ArrayList<SmsMessage>)in.readObject();
    } catch (Exception ex) {
        System.out.println("Error in get method");
    } finally {
        in.close();
        fis.close();
}

此代码不起作用 - 我的意思是当我保存完整的数组列表并终止应用程序时,当我在打开应用程序时尝试再次读取它时它什么也不返回。这里有什么问题?

【问题讨论】:

    标签: android file serialization


    【解决方案1】:

    像这样初始化:

        fout=new FileOutputStream(FILENAME));
    

    out.writeObject(list);添加这一行

         out.flush();   
    

    同样初始化

          fis = new FileInputStream((FILENAME));
    

    希望这可行....你在 logcat 上收到任何错误消息吗??

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 2013-11-13
      • 2013-01-18
      • 2015-09-21
      • 2020-08-02
      • 2013-02-05
      • 1970-01-01
      相关资源
      最近更新 更多