【发布时间】:2015-07-13 23:47:27
【问题描述】:
任务是
创建一个程序来接受和存储来自任何 Winter 的数据 奥运会。 该程序应接受并存储每个赛事最多 6 个参赛者姓名 以及他们参加的活动的名称。它也应该排序 仅显示奖牌获得者的项目得分或次数 他们赢得的奖牌。
我创建了一个运行顺利的“事件”类,但是在尝试将“事件”对象写入文件并读取它们时遇到了问题。
这是我创建新事件的方法:
public static void addEvent() {
File events = new File("events.dat");
Scanner input = new Scanner(System.in);
String eventName;
ArrayList<Event> olympics = new ArrayList<Event>();
boolean fileExists = false;
if (events.exists()) {
fileExists = true;
} else {
try {
events.createNewFile();
System.out.println("File created");
} catch (IOException e) {
System.out.println("File could not be created");
System.err.println("IOException: " + e.getMessage());
}
}
System.out.print("Enter name of event: ");
eventName = input.nextLine();
olympics.add(new Event(eventName));
//write Objects
try {
FileOutputStream out = new FileOutputStream(events, fileExists);
ObjectOutputStream writeEvent = new ObjectOutputStream(out);
writeEvent.writeObject(olympics);
writeEvent.close();
} catch (FileNotFoundException e) {
System.out.println("File could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Problem with input/output.");
System.err.println("IOException: " + e.getMessage());
}
menu();
}// end addEvent()
以及我显示文件的方法:
public static void displayFile(File datFile) {
File events = datFile;
String output ="";
//read objects
try {
FileInputStream in = new FileInputStream(events);
ObjectInputStream readEvents = new ObjectInputStream(in);
ArrayList<Event> recoveredEvents = new ArrayList<Event>();
while (readEvents.readObject() != null) {
recoveredEvents.add((Event)readEvents.readObject());
}
readEvents.close();
for (Event e: recoveredEvents) {
//System.out.println(e + "\n");
output += e + "\n";
}
} catch(FileNotFoundException e) {
System.out.println("File does not exist or could not be found");
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Problem reading file");
System.err.println("IOException: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class could not be used to cast object.");
System.err.println("ClassNotFoundException: " + e.getMessage());
}
System.out.println(output);
menu();
}// end displayFile()
这是一门初级课程,到目前为止,我很难处理文件。编辑:忘了提到当我尝试调用 displayFile() 时它会抛出一个带有消息“null”的 IOException。
【问题讨论】:
标签: java object serialization