javaexport-to-csvopencsv

How to escape linebreak character while writing a csv with java/opencsv


I have a CSV file, which is saved as a Bean. One column has HTML tags including \n character. While reading with opencsv is not a problem, but when i write a new csv it actually creates a new line break/row. CSV

Here is what i have tried:

File file = new File(outDirectory, this.outputCSVName);

    try (
            Writer writer = Files.newBufferedWriter(Paths.get(file.toURI()));
    ) {
        StatefulBeanToCsv<Shopify> beanToCsv = new StatefulBeanToCsvBuilder(writer)
                .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                .withApplyQuotesToAll(true)[![enter image description here][1]][1]
                .withEscapechar('\n')
                .withLineEnd("\n") // just to test
                .withSeparator(',')
                .build();

        beanToCsv.write(data);
        writer.close();

    } catch (CsvRequiredFieldEmptyException | IOException e) {
        throw new RuntimeException(e);
    } catch (CsvDataTypeMismatchException e) {
        throw new RuntimeException(e);
    }

and here is how it looks like in the arraylist:enter image description here

How can i write it as a string? Also how can i export it as a UTF-8 encoded file?


Solution

  • The suggestion of @g00se made me remove the .withEscapechar('\n') and after that it worked fine. My final Export looks like this:

    File file = new File(outDirectory, this.outputCSVName);
    
        try (
                Writer writer = Files.newBufferedWriter(Paths.get(file.toURI()), StandardCharsets.UTF_8);
        ) {
            StatefulBeanToCsv<Shopify> beanToCsv = new StatefulBeanToCsvBuilder(writer)
                    .withSeparator(',')
                    .build();
    
            beanToCsv.write(data);
            writer.close();
            return "Export OK";
        } catch (CsvRequiredFieldEmptyException | IOException e) {
            throw new RuntimeException(e);
        } catch (CsvDataTypeMismatchException e) {
            throw new RuntimeException(e);
        }