The assignment is to
Create a program that accepts and stores data from any Winter Olympics. The program should accept and store up to 6 competitor names for each event as well as the name of the event they participated in. It should also sort the scores or times of the events showing the medal winners only with the medal they won.
I have created an "Event" class which is going smoothly, but I run into problems when trying to write the "Event" objects to a file and read them.
Here is my method to create a new event:
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()
And my method to display the file:
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()
This is a beginning class and handling files has been difficult to wrap my head around so far. Edit: Forgot to mention that it throws an IOException with the message "null" when I try to call displayFile().