Question

In: Computer Science

The purpose of this homework is to test your knowledge of File IO and Collections and...

The purpose of this homework is to test your knowledge of File IO and Collections and the language would be java.

Suppose that we have a file Employee.csv which contains employee information of a certain company.

The first line of the file contains the following header:

employeeId,firstName,lastName,dob,gender,position

After the header line, each employee information is written on a separate line which consists of 6 comma-separated fields, for example:1234567, John, Smith,20/12/1989, M, Software Engineer

Question 1. Write code to read the file and return a list of employee objects.

Question 2. Given a list of employee objects, write code to sort the list by first name and print the sorted list on the console.

Solutions

Expert Solution

This project consists of three classes:
1) Employee Class : This class is a model class for the employees and fileds to store all their information

2) FirstNameSorter : It is a class which implements the Comparator interface which in turn allows us to sort our employee list. It overrides the compare method of the Comparator interface.

3) CSVReader class : This class provides two functions 
                     a) readFile() : This function parses the csv file and reads each line of the csv
                                     file(skipping the header). It then splits the line using ',' 
                                     and creates an employee object with the values retrieved.
                                     Finally it adds the newly created object to the employee list.

                     b) sortEmployeeList() : This function calls the sort method on the employee list
                                             with an object of FirstNameSort as an argument. Finally         
                                             it prints the sorted list.

For any clarifications refer to the code.
Each line has been commented for your reference.

//////////////////////////////////////////
//////////////////////////////////////////
Employee Class
//////////////////////////////////////////

import java.util.Comparator;

public class Employee{
    private String employeeId;
    private String firstName;
    private String lastName;
    private String dob;
    private String gender;
    private String position;


    public Employee(String employeeId, String firstName, String lastName, String dob, String gender, String position) {
        this.employeeId = employeeId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.gender = gender;
        this.position = position;
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

}

//////////////////////////////////////////
//////////////////////////////////////////
Comparator Class
//////////////////////////////////////////

import java.util.Comparator;

public class FirstNameSort implements Comparator<Employee> {
    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getFirstName().compareToIgnoreCase(o2.getFirstName());
    }
}
//////////////////////////////////////////
//////////////////////////////////////////
Main Class
//////////////////////////////////////////
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class CSVReader {


    public static void main(String[] args) {
        //oath to the file that has to be parsed...replace '\' in the path with '\\'
        //Enter your file path here with double \
        String csvFilePath = "D:\\New Text Document.csv";
        //Employee list to store all the records
        List<Employee> employeeList = new ArrayList<>();
        //readFile function reads the contents of the csv file and adds all the records to the employee list
        readFile(csvFilePath, employeeList);
        //function to sort the employee list
        sortEmployeeList(employeeList);

    }

    private static void sortEmployeeList(List<Employee> employeeList) {
        //call the sort method on the arraylist with a comparator argument
        //the comparator argument will be the object of the class FirstNameSort
        employeeList.sort(new FirstNameSort());
        //print all the elements in the employee list
        for (Employee e : employeeList) {
            System.out.println(e.getEmployeeId() + " ," +
                    e.getFirstName() + " ," +
                    e.getLastName() + " ," +
                    e.getDob() + " ," +
                    e.getGender() + " ," +
                    e.getPosition() + "\n");
        }
    }

    private static void readFile(String csvFilePath, List<Employee> employeeList) {
        //declare a buffered reader
        BufferedReader br = null;
        //line will store each record read from the file
        String line = "";
        //since it's a csv file we have to split the string using ',' to get the individual values
        String splitByCharacter = ",";

        try {
            //initialise the buffered reader
            br = new BufferedReader(new FileReader(csvFilePath));
            //since the first lien is the header so we skip it
            br.readLine();
            //if the line read is not null
            while ((line = br.readLine()) != null) {
                //skip the empty lines
                if (line.trim().isEmpty())
                    continue;

                //if the line is not empty, use comma as separator
                String[] record = line.split(splitByCharacter);
                //create the employee object from the values read fromt he file
                Employee empObject = new Employee(record[0], record[1], record[2], record[3], record[4], record[5]);
                //add the object to the employee list
                employeeList.add(empObject);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    //always close the buffered reader
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

Related Solutions

File IO Java question • Ask the user to specify the file name to open for...
File IO Java question • Ask the user to specify the file name to open for reading • Get the number of data M (M<= N) he wants to read from file • Read M numbers from the file and store them in an array • Compute the average and display the numbers and average.
The purpose of this assignment is to enhance your writing, application of knowledge, and critical thinking...
The purpose of this assignment is to enhance your writing, application of knowledge, and critical thinking skills. In general, this assignment requires you to analyze an organization of your choice and prepare a case study covering a variety of aspects of the organization. The content will include information on the mission, strategy, culture, structure, and environment of the organization. First you need to choose an organization to examine. It can be one you worked for in the past, your present...
Binary file IO Suppose a file has been encrypted using the Caesar cipher as described above,...
Binary file IO Suppose a file has been encrypted using the Caesar cipher as described above, and you know the secret key. Write a program to decrypt (or decode) the file. Your program will prompt the user to enter an input file name for the encrypted file, an output file name for the unencrypted version of the input file, and the secret key. Create a DataInputStream for the input file and a DataOutputStreams for the output file. Next, read the...
PURPOSE: The purpose of this assignment is to enable the students to enhance their knowledge on...
PURPOSE: The purpose of this assignment is to enable the students to enhance their knowledge on the environmental engineering and sustainable development for environmental engineering. TASK 1 (DOCUMENTATION) Development in science and technology has increase the level of human lifestyle which leads to technology advancement. However, everything good comes with a price. One of the greatest problems that the world is facing today is that of environmental pollution, increasing with every passing year and causing grave and irreparable damage to...
ok here is my homework This assignment focuses on file streams. Your program will accept the...
ok here is my homework This assignment focuses on file streams. Your program will accept the name of an input file from the user, and the name of an output file from the user. You may assume the input file contains no more than 100 lines. Your program will write the lines of the input file to the output file in reverse line order, i.e. the first line of the input file becomes the last line of the output file,...
Purpose: To strengthen and demonstrate your knowledge of the Immune and Lymphatic System and its systemic...
Purpose: To strengthen and demonstrate your knowledge of the Immune and Lymphatic System and its systemic relationship in the body. The ability to apply this content and think systemically with physiology processes will benefit you as a healthcare student and practitioner. Criteria for Success: To be successful you will make sure you complete diagrams as instructed in the tasks, including proper values (if required) on the x & y-axis as well as labeling those. You also need to make sure...
The purpose of this problem set is to reinforce your knowledge of some basic chemical concepts...
The purpose of this problem set is to reinforce your knowledge of some basic chemical concepts that are important for the origin of the elements. 1. Use the abundances of the stable isotopes of strontium and the masses of these nuclides (found at http://atom.kaeri.re.kr/nuchart/) to calculate the atomic weight of strontium. Compare the value that you get with the value shown in the periodic table found at http://www.rsc.org/periodic-table. Show your work. 2. Consult the chart of the nuclides (http://atom.kaeri.re.kr/nuchart/ )...
Purpose: To strengthen and demonstrate your knowledge of the Immune and Lymphatic System and its systemic...
Purpose: To strengthen and demonstrate your knowledge of the Immune and Lymphatic System and its systemic relationship in the body. The ability to apply this content and think systemically with physiology processes will benefit you as a healthcare student and practitioner. Criteria for Success: To be successful you will make sure you complete diagrams as instructed in the tasks, including proper values (if required) on the x & y-axis as well as labeling those. You also need to make sure...
Write a 800 word essay. The purpose is to demonstrate your knowledge about principles of macroeconomics...
Write a 800 word essay. The purpose is to demonstrate your knowledge about principles of macroeconomics and ability to apply these principles to issues in the real world. It should be as analytical as possible; you should avoid merely describing the issue or simply repeating work by other authors. You have to pick a company and show how macroeconomic developments impact its business. It can be about trade, foreign exchange rates, foreign direct investments, financial criris or something else.
Now, it is time for you to test your knowledge of key economic indicators and the...
Now, it is time for you to test your knowledge of key economic indicators and the effects of economic measurements have on an economy. The purpose of this assignment is to investigate and to gauge your understanding of key economic indicators by filling out the figure one (1) below and to write up your findings and compare and contrast the United States to that of China. Compare and Contrast the United States to that of China Assignment should include the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT