gpt4 book ai didi

java - 无法使用对象列表写入/读取文件

转载 作者:行者123 更新时间:2023-11-29 20:33:03 25 4
gpt4 key购买 nike

我正在尝试将对象列表保存到文件中,但每当我尝试从文件中读取时总是失败。谁能告诉我我做错了什么

写入它

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

这是事件类

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;
}
}

最佳答案

是的,EventsClass 需要可序列化才能写入存储。如果你有它实现 java.io.Serializable,那么一切都应该适合你。 Here is a decent tutorial您更了解 java 序列化的情况。

关于java - 无法使用对象列表写入/读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31712083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com