简体   繁体   English

Java opencsv CsvToBean构造函数

[英]Java opencsv CsvToBean constructor

I'm trying to create a list of objects using opencsv's CsvToBean. 我正在尝试使用opencsv的CsvToBean创建对象列表。 I have two different classes: address (address) and location (standort). 我有两个不同的类:地址(地址)和位置(standort)。 In the class location I'm trying to create an object address. 在类位置中,我试图创建一个对象地址。

public class CSV {
public List<StandortAuto> readAutos() {
    CsvToBean<StandortAuto> csvToBean = new CsvToBean<StandortAuto>();

    Map<String, String> columnMapping = new HashMap<String, String>();
    columnMapping.put("Strasse", "strasse");
    columnMapping.put("Parkplaetze", "parkplaetze");

    HeaderColumnNameTranslateMappingStrategy<StandortAuto> strategy = new HeaderColumnNameTranslateMappingStrategy<StandortAuto>();
    strategy.setType(StandortAuto.class);
    strategy.setColumnMapping(columnMapping);

    List<StandortAuto> list = null;
    CSVReader reader;
    try {
        reader = new CSVReader(new FileReader(new File("/Users/fabich/Projects/LeihAuto/src/com/hwz/leihauto/csv/cars.csv")),',');
        System.out.println(reader.getLinesRead());
        list = csvToBean.parse(strategy, reader);
        System.out.println(list.size());
        for (StandortAuto s : list) {
            System.out.println(s.getName());
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return list;
}
}

How can I read from a CSV file using opencsv creating a list of location objects each containing an address? 如何使用opencsv从CSV文件读取内容,以创建每个包含地址的位置对象列表?

Thanks a lot for your help 非常感谢你的帮助

Sorry but the CsvToBean is a one to one translation. 抱歉,CsvToBean是一对一的翻译。 One line in the csv file becomes one object. csv文件中的一行变成一个对象。

I had a similar situation when using openCSV, what we did was introduce a DTO (Data Transfer Object) that was all the data in the CSV file then we created a translator class that would take the DTO object and build the Location object with Address object inside. 在使用openCSV时,我遇到了类似的情况,我们要做的是引入一个DTO(数据传输对象),它是CSV文件中的所有数据,然后我们创建了一个转换程序类,该类将使用DTO对象并使用Address对象构建Location对象内。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM