Question: Exception Handling and File I/O In this guided lab you will learn how to read data from a formatted file where each line in a
Exception Handling and File I/O
In this guided lab you will learn how to read data from a formatted file where each line in a file represents a record and within each record there are many fields containing data. All data retrieved will be saved in objects with the same number and type of fields.
First, we build a class called FlightRecord, encapsulating a flight record as reflected by the data in the file. Each line read from the file will be parsed and used to instantiate a FlightRecord object. Since we do not know how many lines (i.e., how many flight records) are in the file, we place all the flight records into an ArrayList object as opposed to a fixed-length array.
Step1 : Prepare the required file needed to complete the lab
- Create a textfile named flights.txt containing the three lines as shown below. Save the file in your favorite directory and remember the file path.
AA123,BWI,SFO,235,239.5
AA200,BOS,JFK,150,89.3
AA900,LAX,CHI,201,201.8
Step2: Create the FlightRecord class
/* The FlightRecord class */
public class FlightRecord
{
private String flightNumber; // ex. = AA123
private String origin; // origin airport; ex. = BWI
private String destination; // destination airport; ex. = SFO
private int numPassengers; // number of passengers
private double avgTicketPrice; // average ticket price
/** Constructor with parameters */
public FlightRecord( String flightNumber, String origin, String destination, int numPassengers, double avgTicketPrice )
{
this.flightNumber = flightNumber;
this.origin = origin;
this.destination = destination;
this.numPassengers = numPassengers;
this.avgTicketPrice = avgTicketPrice;
}
/** toString flight number, origin, destination, number of passengers, and average ticket price */
@Override
public String toString( )
{ return "Flight " + flightNumber + ": from " + origin + " to " + destination + " \t" + numPassengers + " passengers"
+ "; average ticket price: " + avgTicketPrice );
}
// accessors, mutators, and other methods
}
Step 3 Demonstrating How to Read Structured Data from a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.ArrayList;
// or replace all imports with import java.io.* and import java.util.*
public class ReadFlights
{
public static void main( String [ ] args )
{
// instantiate ArrayList to hold FlightRecord objects
ArrayList
try
{
Scanner file = new Scanner( new File( "flights.txt" ) ); // If you saved the file in different directory than java
// working directory, you have to include it with the file name.
while ( file.hasNext( ) ) // test for the end of the file
{ // read a line
String stringRead = file.nextLine( );
// process the line read
Scanner parse = new Scanner( stringRead );
parse.useDelimiter( "," ); // the fields are separated by a ,
String flightNumber = parse.next( );
String origin = parse.next( );
String destination = parse.next( );
try
{ int numPassengers = parse.nextInt( );
double avgTicketPrice = parse.nextDouble( );
FlightRecord frTemp = new FlightRecord( flightNumber, origin, destination, numPassengers, avgTicketPrice );
listFlightRecords.add( frTemp ); //add FlightRecord obj to listFlightRecords
}
catch ( InputMismatchException ime )
{ System.out.println( "Error in flight record: " + stringRead + "; record ignored" ); }
} // end of while
file.close( ); // release resources associated with flights.txt
}
catch ( FileNotFoundException f )
{ System.out.println( "Unable to find flights.txt" ); }
catch ( Exception e )
{ e.printStackTrace( ); }
// print the FlightRecords read
for ( FlightRecord flight : listFlightRecords ) System.out.println( flight );
}
}
Application
Read Employees data from a formatted text file called employeesRecords.txt where each record contains information about one employee ( the id, firstname, lastname, city and salary). An example of employee record is:
334:Eric:Hallam:Montreal:82000
- Save all retrieved records into an arrayList then display the data record of the employee with the highest salary.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
