jeudi 15 février 2018

Best design for Java Parsing several CSV files with different headers and model objects

I have several CSV files that I will need to Parse. and use later for Insert in MYSQL. I have already written one parser but I do not want to code to be duplicated.

I have already in mind that I should use an abstract class, or maybe a Factory but I can't really put a finger on the best way to design this.

So this is my parser :

public class LocusAliasCsvParser {

**private static final String[] FILE_HEADER_MAPPING = {"id", "locusID", "organismid", "variable", "alias"};**

**private static final String ID = "id";
private static final String LOCUS_ID = "locusID";
private static final String ORGANISM_ID = "organismid";
private static final String VARIABLE = "variable";
private static final String ALIAS = "alias";**


public static **List<AliasLocus>** readCsvFile(String fileName) {

    FileReader fileReader = null;
    CSVParser csvFileParser = null;

    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
    **List<AliasLocus> aliases = new ArrayList();**

    try {
        fileReader = new FileReader(fileName);
        csvFileParser = new CSVParser(fileReader, csvFileFormat);

        //Get a list of CSV file records
        List csvRecords = csvFileParser.getRecords();

        //Read the CSV file. Header is ignored (i == 1)
        for (int i = 1; i < csvRecords.size(); i++) {
            CSVRecord record = (CSVRecord) csvRecords.get(i);

            **AliasLocus aliasLocus = new AliasLocus(Integer.parseInt(record.get(ID)),
                    record.get(LOCUS_ID),
                    record.get(ORGANISM_ID),
                    record.get(VARIABLE),
                    record.get(ALIAS));**

            aliases.add(aliasLocus);
        }

    } catch (Exception e) {
        System.out.println("Error in CsvFileReader !!!");
        e.printStackTrace();
    } finally {
        try {
            fileReader.close();
            csvFileParser.close();
        } catch (IOException e) {
            System.out.println("Error while closing fileReader/csvFileParser !!!");
            e.printStackTrace();
        }
    }

    return aliases;
}

The things in BOLD are the changing parts.

does anyone can suggest the best design patters or structure to use to have the least code duplication?

thanks

Aucun commentaire:

Enregistrer un commentaire