如何读取 java 中不整洁的 csv 文件并创建对象的相应 ArrayList?

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

我想读这个csvFile into an array of Flight class objects in which each index will refer to an object containing a record from the csvFile

这是 飞行 class 的蓝图。它不完整,所以我只提供数据成员。

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;

}

我想实现类似这样的功能:

public class DataManager {



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

}

欢迎随时修改,请帮助我。 :)

提前致谢。

您可以尝试 OpenCSV 框架。

看看这个例子:

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();
            }
        }
    }
}

编辑 1:

解析日期:

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
}