【发布时间】:2016-02-26 06:43:03
【问题描述】:
在这个问题上坚持了几天,我觉得这一切都是正确的。我目前甚至无法在 Android 设备监视器中看到正在创建的文件。
我正在尝试一次将一个事件对象写入文件,并在任何给定时间读回所有事件。
事件类
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 类
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;
}
【问题讨论】:
标签: java android serialization