我正在尝试将对象列表保存到文件中,但每当我尝试从文件中读取时,它总是会失败。有人能告诉我我做错了吗
写给它
public void writeToFile(List<EventsClass> list)
{
String filename = "events.srl";
ObjectOutput out = null;
try
{
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
out.writeObject(list);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
我检查过,参数列表总是包含一个对象列表
从中读取
public List<EventsClass> readFromFile()
{
ObjectInputStream input;
String filename = "events.srl";
try
{
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
List<EventsClass> list = (List<EventsClass>) input.readObject();
input.close();
return list;
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
总是无法读取文件并返回null
这是EventsClass
public class EventsClass
{
private String eventName;
private String eventClass;
private String eventDate;
private int eventMonth;
private int eventDay;
public EventsClass(String eventClass, String eventName, String eventDate, int eventMonth, int eventDay)
{
this.eventClass = eventClass;
this.eventName = eventName;
this.eventDate = eventDate;
this.eventMonth = eventMonth;
this.eventDay = eventDay;
}
public void putEventData(String mClass, String name, String date, int month, int day)
{
this.eventClass = mClass;
this.eventName = name;
this.eventDate = date;
this.eventMonth = month;
this.eventDay = day;
}
public String getEventClass()
{
return eventClass;
}
public String getEventName()
{
return eventName;
}
public String getEventDate()
{
return eventDate;
}
public int getEventMonth()
{
return eventMonth;
}
public int getEventDay()
{
return eventDay;
}
}
答案 0 :(得分:2)
Ya,EventsClass需要可序列化才能写入存储。如果你实现了java.io.Serializable
,那么一切都应该适合你。 Here is a decent tutorial您更了解java序列化的内容。