简体   繁体   中英

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.

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

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); should be changed to 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).

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?

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. To read objects you should just split String from this file by separator and parse each JSON to your object separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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