Question

In: Computer Science

* readCsvFile() -- Read in a CSV File and return a list of entries in that...

* readCsvFile() -- Read in a CSV File and return a list of entries in that file.
   * @param filePath -- Path to file being read in.
   * @param classType -- Class of entries being read in.
   * @return -- List of entries being returned.
   */
   public <T> List<T> readCsvFile(String filePath, Class<T> classType){
       return null;
   }

implement this class. Return a list of T type. dont worry about CSV format. Just assume there is a constructor for the class type and it has 3 elements. make something up

Solutions

Expert Solution

Below is the complete program to run and test the method (readCsvFile) using Employee class. You can use any other class as per your requirement which has a public constructor with three arguments. I have mentioned inline comments as well.

Note: Don't forget to change the classes specified in parameterTypes variable according to the data type of variables in your class. Order of parameters should be same in parameterTypes variable as specified in the constructor.

Employee.java

public class Employee {

    Integer id;
    String fname, lname;

    public Employee(Integer id, String fname, String lname) {
        this.id = id;
        this.fname = fname;
        this.lname = lname;
    }

    @Override
    public String toString() {
        return "Employee{" + "id = " + id + ", fname = " + fname +
                ", lname = " + lname + "}";
    }
}

Test.java to run and test the code

import java.io.*;
import java.util.*;

public class Test {
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        List<Employee> empList =  test.readCsvFile("src/test.csv", Employee.class);
        empList.stream().forEach(System.out::println);
    }

    public <T> List<T> readCsvFile(String filePath, Class<T> classType) throws Exception {
        List<T> result = new ArrayList<>();
        //open input stream to read from the file
        BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));
        String line;
        while ((line = reader.readLine()) != null) {
            //split the line from comma. CSV file has comma(',') as default value separator
            String[] splitString = line.split(",");
            //declare parameter types accepted by the constructor
            //update it as per your class, i have considered the constructor which takes 2 String and 1 Integer parameters
            Class[] parameterTypes = new Class[]{Integer.class, String.class, String.class};
            //set the values from splitString array which is read from csv file
            Object[] values = new Object[3];
            values[0] = Integer.parseInt(splitString[0].trim());
            values[1] = splitString[1].trim();
            values[2] = splitString[2].trim();
            T t = classType.getConstructor(parameterTypes).newInstance(values);
            result.add(t);
        }
        //close the connection with input stream
        reader.close();
        return result;
    }
}

Test.csv File:

Screenshot of code:

Output:


Related Solutions

build a python program that will be performing: - Read a CSV file 'annual.csv' enterprise into...
build a python program that will be performing: - Read a CSV file 'annual.csv' enterprise into a data structure - Count the number of rows and columns - Determine if the data contains empty values - Replace the empty values by 'NA' for strings, '0' for decimals and '0.0' for floats - Transform all Upper case characters to Lower case characters - Transform all Lower case characters to Upper case characters - save back the 'repaired' array as csv -...
Write a Java program to read in the 10 numbers in the example file Book1.csv provided...
Write a Java program to read in the 10 numbers in the example file Book1.csv provided above. The program should sum all the numbers, find the lowest number, find the highest number, and computer the average. Upon completion of the processing, the program should write a new text file named stats.txt with the information found in the following format where xxx represents a number calculated above. The sum of the numbers is: xxx The lowest number is: xxx The highest...
how to read a csv file in php and make a html table? I can't use...
how to read a csv file in php and make a html table? I can't use the PHP function fgetcsv. I can use explode. I can't put a php inside a php. Acme,Walmart,Ross,BJs,Target,Marshalls,Foot Locker,Giant,Charming Charlie 142,160,28,10,5,3,60,0.28,3167 175,180,18,8,4,1,12,0.43,4033 129,132,13,6,3,1,41,0.33,1471 138,140,17,7,3,1,22,0.46,3204 232,240,25,8,4,3,5,2.05,3613 135,140,18,7,4,3,9,0.57,3028 150,160,20,8,4,3,18,4.00,3131 207,225,22,8,4,2,16,2.22,5158 271,285,30,10,5,2,30,0.53,5702 89,90,10,5,3,1,43,0.30,2054 153,157,22,8,3,3,18,0.38,4127 87,90,16,7,3,1,50,0.65,1445 234,238,25,8,4,2,2,1.61,2087 106,116,20,8,4,1,13,0.22,2818 175,180,22,8,4,2,15,2.06,3917 165,170,17,8,4,2,33,0.46,2220 166,170,23,9,4,2,37,0.27,3498 136,140,19,7,3,1,22,0.63,3607 <!DOCTYPE html> <html> <head>    <meta charset="utf-8">    <title>Stores</title>    <link rel="stylesheet" href="style.css"> </head> <body> <h1>Stores</h1> <?php <table> <tr> <th>Acme</th> <th>Walmart</th> <th>Ross</th> <th>BJs</th> <th>Target</th> <th>Marshalls</th> <th>Foot Locker</th>...
How to read the given structure from a random CSV file separated by commas(which contains no...
How to read the given structure from a random CSV file separated by commas(which contains no headers only the values of the contents of the structure) and then insert in a binary search tree using one of the structure contents as a key i.e. datetime and handle duplicates in binary search tree by implementing link_list.Please develop a C code for this. struct data{ char biker_id[200]; char distance_bike_travelled[200]; char datetime[200]; char count_tripr[200]; }
What is a csv file and how does database work in general?
What is a csv file and how does database work in general?
How to read a text file and store the elements into a linked list in java?...
How to read a text file and store the elements into a linked list in java? Example of a text file: CS100, Intro to CS, John Smith, 37, 100.00 CS200, Java Programming, Susan Smith, 35, 200.00 CS300, Data Structures, Ahmed Suad, 41, 150.50 CS400, Analysis of Algorithms, Yapsiong Chen, 70, 220.50 and print them out in this format: Course: CS100 Title: Intro to CS Author: Name = John Smith, Age = 37 Price: 100.0. And also to print out the...
Question6: Write a program to read the file 202010mid.txt, store the content in a list of...
Question6: Write a program to read the file 202010mid.txt, store the content in a list of tuples, then print the list. [6 marks] Question7: Write Python code to do the following operations using request library. [12 marks] Check if the following webpage is available or not: https://edition.cnn.com/news.html [4 marks] Send a get request to the following webpage and show the result: http://api.open-notify.org/iss-pass.json [4 marks] The webpage from part 2 is expecting some parameters as shown from the results. Now create...
You are required to read in a list of stocks from a text file “stocks.txt” and...
You are required to read in a list of stocks from a text file “stocks.txt” and write the sum and average of the stocks’ prices, the name of the stock that has the highest price, and the name of the stock that has the lowest price to an output file. The minimal number of stocks is 30 and maximal number of stocks in the input file is 50. You can download a input file “stocks.txt” from Canvas. When the program...
In this program you will read a file specifying a directed graph G as a list...
In this program you will read a file specifying a directed graph G as a list of edges. Each edge u →v is listed on one line as u v. The input file simply lists the edges in arbitrary order as pairs of vertices, with each edge on a separate line. The vertices are numbered in order from 1 to the total number of vertices. The program outputs the out-degree sequence for GSCC in increasing order. For example for the...
In this program you will read a file specifying a directed graph G as a list...
In this program you will read a file specifying a directed graph G as a list of edges. Each edge u →v is listed on one line as u v. The input file simply lists the edges in arbitrary order as pairs of vertices, with each edge on a separate line. The vertices are numbered in order from 1 to the total number of vertices. The program outputs the out-degree sequence for GSCC in increasing order. For example for the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT