简体   繁体   English

如何将类对象读/写到内部Android文件?

[英]How to Read/Write a Class Object to an Internal Android File?

Been stuck on this for a few days, and it all seems right to me. 坚持了几天,这对我来说似乎是正确的。 I am currently unable to even see a file being created in the Android device monitor. 目前,我什至无法在Android设备监视器中看到正在创建的文件。

I am trying to write an event object to a file one at a time, and read back all of the events at any given time. 我试图一次将一个事件对象写入一个文件,并在任何给定时间读回所有事件。

Event Class 活动类

public class Event implements Serializable {

private static final long serialVersionUID = -29238982928391l;

public String time;
public String drug;
public Date date;
public int dose;

SimpleDateFormat format = new SimpleDateFormat("MM-dd");

public Event(Date date, String time, String drug, int dose){
    this.time = time;
    this.drug = drug;
    this.date = date;
    this.dose = dose;
}

Events Class <- Controls all events, this class is used by my MainActivity class 事件类 <-控制所有事件,我的MainActivity类使用该类

public class Events {

ArrayList<Event> eventslist = new ArrayList<Event>();
String saveFileName = "calendarEvents.data";
Context context;



public Events(Context ctx) {
    super();
    context = ctx;
}


// Reads the events for a given day
public ArrayList<Event> readData(Date event_date) {
    ArrayList<Event> dayEvents = new ArrayList<Event>();

    for (Event entry : eventslist) {
        Date d = entry.getDate();

        if(d.compareTo(event_date) == 0){
            dayEvents.add(entry);
        }
    }
    return dayEvents;
}


public ArrayList<Event> readAllEvents() {
    return eventslist;
}


//inserts an event into the array
// this is what calls save()
public int insertData(Date date, String time, String drug, int dose) {
    Event e = new Event(date, time, drug, dose);

    try {
        save(saveFileName, e);
        eventslist.add(e);
    } catch (Exception ex){
        ex.printStackTrace();
        return -1;
    }
    return 1;
}


//My actual write function
public void save(String filename, Event theObject) {
    FileOutputStream fos;
    ObjectOutputStream oos;

    try {
        fos = context.openFileOutput(filename, Context.MODE_APPEND);
        oos = new ObjectOutputStream(fos);

        theObject.writeObject(oos);
        oos.close();
        fos.close();
    } catch(IOException e){
        e.printStackTrace();
    }
}

//my read function, not called in this example
public ArrayList<Event> readFile(String filename, Context ctx) {
    FileInputStream fis;
    ObjectInputStream ois;
    ArrayList<Event> ev = new ArrayList<Event>();

    try {
        fis = ctx.openFileInput(filename);
        ois = new ObjectInputStream(fis);

        while(true) {
            try{
                ois.readObject();
                //ev.add();
            } catch (NullPointerException | EOFException e){
                e.printStackTrace();
                ois.close();
                break;
            }
        }
        ois.close();
        fis.close();
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }

    return ev;



}

It seems theObject.writeObject(oos); 似乎theObject.writeObject(oos); should be changed to oos.writeObject(theObject); 应该更改为oos.writeObject(theObject);

I think you have defined methods named readObject/writeObject in class Event .But what you should know is these two methods are reflected and called by ObjectInputStream/ObjectOutputStream, you should not call it directly from outside(So please make these two methods private). 我认为您已经在Event类中定义了名为readObject/writeObject方法,但是您应该知道这两个方法是由ObjectInputStream / ObjectOutputStream反映和调用的,因此您不应直接从外部调用它(因此请使这两个方法私有)。

Appending new object to serialized file will corrupt it cause for each object it writes specific metadata. 将新对象附加到序列化文件将损坏它,因为它会为每个对象写入特定的元数据。 You can read more about it at Object Serialization Stream Protocol . 您可以在“ 对象序列化流协议”中了解有关它的更多信息。

I'd suggest to use another type of serialization to store objects. 我建议使用另一种类型的序列化来存储对象。 You can do it with JSON : How to insert one more item in a json existing structure with gson? 您可以使用JSON进行操作: 如何使用gson在json现有结构中插入另一个项目?

Or as your object format is quite simple you can even serialize it to JSON and append to file one by one with unique separator after each object. 或者,因为您的对象格式非常简单,您甚至可以将其序列化为JSON,并在每个对象之后使用唯一的分隔符将其一一追加到文件中。 To read objects you should just split String from this file by separator and parse each JSON to your object separately. 要读取对象,您应该使用分隔符从此文件中拆分String并将每个JSON分别解析为您的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM