Lecture d'un fichier CSV

PHOTO EMBED

Fri Jul 21 2023 17:22:34 GMT+0000 (Coordinated Universal Time)

Saved by @ambre

import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvValidationException;
import fr.dalkia.crt.importdata.reglages.exceptions.CsvException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Service
public class CsvService {

    private static final Character SEPARATOR_SEMICOLON = ';';

    public List<List<String>> extractData(Path path, int nbLines) throws CsvException {
        try (Reader reader = Files.newBufferedReader(path); var csvReader = initCsvReader(reader)) {
            return readCsv(nbLines, csvReader);
        } catch (IOException | CsvValidationException exception) {
            CsvException csvException = new CsvException("CSV_ERROR", "Problème à la lecture du fichier csv " + path + ": " + exception.getMessage());
            csvException.initCause(exception);
            throw csvException;
        }
    }

    private static CSVReader initCsvReader(Reader reader) {
        return new CSVReaderBuilder(reader)
                .withSkipLines(1)
                .withCSVParser(new CSVParserBuilder()
                        .withSeparator(SEPARATOR_SEMICOLON)
                        .withIgnoreQuotations(true)
                        .build())
                .build();
    }

    private static List<List<String>> readCsv(int nbLines, CSVReader csvReader) throws IOException, CsvValidationException {
        List<List<String>> dataExtracted = new LinkedList<>();
        String[] line;
        int lineNumber = 0;
        while ((line = csvReader.readNext()) != null && lineNumber < nbLines) {
            dataExtracted.add(Arrays.asList(line));
            log.trace("Extraction de la ligne {}", Arrays.toString(line));
            lineNumber++;
        }
        return dataExtracted;
    }
}
content_copyCOPY