1

I´m new to OpenCSV here and I´m trying to parse a CSV file received in a REST service.

Here´s my code:

    CSVReader csvReader = new CSVReader(new InputStreamReader(csv), ';', CSVParser.DEFAULT_QUOTE_CHARACTER);

    HeaderColumnNameTranslateMappingStrategy<TesteBean> strategy = new HeaderColumnNameTranslateMappingStrategy<>();
    Map<String, String> columnMap = new HashMap<>();
    columnMap.put("NOME", "nome");
    columnMap.put("VALOR", "valor");
    strategy.setColumnMapping(columnMap);
    strategy.setType(TesteBean.class);
    CsvToBean<TesteBean> csvToBean = new CsvToBean<>();
    List<TesteBean> beanList = csvToBean.parse(strategy, csvReader);
    for (TesteBean bean : beanList) {
        System.out.println(bean.getNome());
        System.out.println(bean.getValor());
    }

    List<String[]> rows = csvReader.readAll();
    System.out.println("******* Below this, works fine and prints the values!!");
    for (String[] line : rows) {

        System.out.println("Linha:");
        for (int i = 0; i < line.length; i++) {
            System.out.println(line[i]);
        }
    }

    csvReader.close();

Also, here´s my javabean used:

public class TesteBean {

@CsvBind
private String valor;

@CsvBind
private String nome;

public String getValor() {
    return valor;
}

public String getNome() {
    return nome;
}

public void setValor(String valor) {
    this.valor = valor;
}

public void setNome(String nome) {
    this.nome = nome;
}

}

Also, here´s my CSV file:

NOME;VALOR;
Cliente;Valor_Cliente;
Financeira;Valor_Financeira;

But when I check values in beanList variable, they´re all NULL.

Any ideas? Thanks a lot

Rafael Barioni
  • 183
  • 1
  • 1
  • 12
  • What type is the variable `csv`? InputStream? – ManoDestra Apr 25 '16 at 20:00
  • I just tried running a test on the code above and it worked fine. The `csvReader.readAll()` line didn't work, but then that's no surprise given that it's not the default separation character of a comma. – ManoDestra Apr 25 '16 at 20:20
  • Addendum to my previous comment: the readAll() only works if the reader hasn't read the input before calling readAll(). After I commented out the first way of doing it, it then ran fine. So, both methods work fine :) – ManoDestra Apr 25 '16 at 20:29
  • Yes..csv variable is a InputStream...but the first 2 output commands printed the values? Here they don´t..I only get NULL values... – Rafael Barioni Apr 26 '16 at 11:00
  • Both methods work. I've tried them both and they both work, either filling beans or reading all the rows as string arrays. With exactly the inputs and code that you've described above. – ManoDestra Apr 26 '16 at 13:13
  • What version of OpenCSV are you using? I'm using 3.7. You do realize that you can't use both methods, right? Only one will work at any given time. Once you've read the CSV, it's read. You want to read it again, then you need to code it to do so. – ManoDestra Apr 26 '16 at 13:25

0 Answers0