Question: May you please seperate this code into different methods, one for creating the file and one for reading and then call both methods to the

May you please seperate this code into different methods, one for creating the file and one for reading and then call both methods to the main method? Thank you.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

import java.io.*; import java.util.Scanner; class Athlete implements java.io.Serializable // serializable class { String name; // member data declaration int year; double time;

// parameterized constructor public Athlete(String name, int year, double time) { super(); this.name = name; this.year = year; this.time = time; }

} public class FileExample { public static void main(String aa[]) throws IOException { int count = 0; try { FileOutputStream fi = new FileOutputStream("athlete.ser"); // create athlete.ser file ObjectOutputStream out = new ObjectOutputStream(fi); // pass fi in ObjectOutputStream FileInputStream file = new FileInputStream("athlete.txt"); // open file to read Scanner ss = new Scanner(file); // read from file while (ss.hasNextLine()) // check the line is available or not { String rec[] = ss.nextLine().split(","); // read and split the line // create Athlete object Athlete a = new Athlete(rec[0], Integer.parseInt(rec[1]), Double.parseDouble(rec[2])); out.writeObject(a); // write to file count++; // increment the count }

out.close(); // close all objects file.close(); ss.close(); fi.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Athlete al; // empty reference Athlete variable

try { FileInputStream fi1 = new FileInputStream("athlete.ser"); // open file to read ObjectInputStream in = new ObjectInputStream(fi1); al = (Athlete) in.readObject(); // read object while (count >= 0) { // print values System.out.printf("%-20s%-8d%10.2f", al.name, al.year, al.time); System.out.println(); al = (Athlete) in.readObject(); count--; } fi1.close(); in.close(); // handle all exceptions } catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (EOFException e) { System.out.println(""); } catch (IOException e) {

e.printStackTrace(); }

} }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!