Search code examples
javacsvopencsv

How to read a untidy csv file in java and create a corresponding ArrayList of an object?


I want to read this csvFile into an array of Flight class objects in which each index will refer to an object containing a record from the csvFile.

Here is a blueprint of Flight class. Its not complete so I am only providing the data memebers.

public class Flight {
  private String flightID;
  private String source;
  private String destination;
  private <some clas to handle time > dep;
  private <some clas to handle time> arr;
  private String[] daysOfWeek;
  private <some clas to handle date> efff;
  private <some clas to handle date> efft;
  private <some clas to handle dates> exc;

}

I want to implement a function something like :

public class DataManager {



public List<Flight> readSpiceJet() {
    return new ArrayList<Flight>(); 
}

}

Feel free to modify this and please help me. :)

Thanks in advance.


Solution

  • You can try OpenCSV Framework.

    Have a look at this example:

    import java.io.FileReader;
    import java.util.List;
    
    import com.opencsv.CSVReader;
    import com.opencsv.bean.ColumnPositionMappingStrategy;
    import com.opencsv.bean.CsvToBean;
    
    public class ParseCSVtoJavaBean 
    {
        public static void main(String args[])
        {
            CSVReader csvReader = null;
    
            try
            {
                /**
                 * Reading the CSV File
                 * Delimiter is comma
                 * Default Quote character is double quote
                 * Start reading from line 1
                 */
                csvReader = new CSVReader(new FileReader("Employee.csv"),',','"',1);
                //mapping of columns with their positions
                ColumnPositionMappingStrategy mappingStrategy = 
                        new ColumnPositionMappingStrategy();
                //Set mappingStrategy type to Employee Type
                mappingStrategy.setType(Employee.class);
                //Fields in Employee Bean
                String[] columns = new String[]{"empId","firstName","lastName","salary"};
                //Setting the colums for mappingStrategy
                mappingStrategy.setColumnMapping(columns);
                //create instance for CsvToBean class
                CsvToBean ctb = new CsvToBean();
                //parsing csvReader(Employee.csv) with mappingStrategy  
                List empList = ctb.parse(mappingStrategy,csvReader);
                //Print the Employee Details
                for(Employee emp : empList)
                {
                    System.out.println(emp.getEmpId()+"   "+emp.getFirstName()+"   "
                            +emp.getLastName()+"   "+emp.getSalary());
    
                }
            }
            catch(Exception ee)
            {
                ee.printStackTrace();
            }
            finally
            {
                try
                {
                    //closing the reader
                    csvReader.close();
                }
                catch(Exception ee)
                {
                    ee.printStackTrace();
                }
            }
        }
    }
    

    EDIT 1:

    To parse dates:

    String dateString;
    Date date;
    
    public void setDateString(String dateString) {
     // This method can parse the dateString and set date object as well
    }
    
    public void setDate(Date date) {
         //parse here
    }