In: Computer Science
* 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
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: