Can't use custom seperator in opencsv

452 Views Asked by At

I need to get the values from my csv file and for this I need to set the seperator to ';' and the values are in '"'.

If I try it like this:

    final CSVReader reader = new CSVReader(new FileReader("file"), ';', '"', 1);

    String[] nextLine;
    while ((nextLine = reader.readNext()) != null) {
        if (nextLine != null) {
            System.out.println(Arrays.toString(nextLine));
        }
    }

The compiler gives me this error The constructor CSVReader(FileReader, char, char) is undefined

If I use it without the ';', '"', 1. I get everything that is in my file but it has a strange output.

My file got 10000 values like:

"00026";"01402118";"Zeitsoldat/in" "00027";"11101118";"Ackerarbeiter/in"

and the output looks like: [00026";"01402118";"Zeitsoldat/in] [00027";"11101118";"Ackerarbeiter/in]

1

There are 1 best solutions below

0
JANO On BEST ANSWER

The problem is probably that your code works for older versions of opencsv. I tested your code with 3.3 and it works perfectly. I then looked into what is different in a newer version (5.5.2). I noticed that the creation of the CSVReader differs a lot. Following code works for the new version:

CSVParser parser = new CSVParserBuilder().withSeparator(';').withQuoteChar('"').build();
CSVReader reader = new CSVReaderBuilder(new FileReader("input_files/input.csv"))
        .withSkipLines(1)
        .withCSVParser(parser)
        .build();

String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
    if (nextLine != null) {
        System.out.println(Arrays.toString(nextLine));
    }
}

Output:

[00026, 01402118, Zeitsoldat/in]
[00027, 11101118, Ackerarbeiter/in]

So, in order to solve your problem you have to find the right code for your version. If you use the newest version, you can simply copy above code.