简体   繁体   中英

Java - line break escape in CSV

I am trying to export the data from database to a CSV file using below code. I am able to generate below result using below code but this is not the result I want

Wrong Result: 
    1. "abcd","123","123","test","abcd","123"
    2. "abcd12","222", "333", "testing", "abc", "ccc"
    3. "abc123", "22 : 
        sdds", "sds", "s123", "54"

The first two row result is correct. However, in the 3rd row, the line break occur when a special character : appear in the 2nd cell of row 3. The result I am looking for is: Are there any suggestion I can generate below result by using below code?

Expected Result
1. "abcd","123","123","test","abcd","123"
2. "abcd12","222", "333", "testing", "abc", "ccc"
3. "abc123", "22 : sdds", "sds", "s123", "54"

Code:

try (Writer out = new PrintWriter(path, "UTF-8");
            CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT.RFC4180.withHeader(resultSet).withQuoteMode(QuoteMode.ALL))) {


                while(resultSet.next()) {   
                    final List<String> columnList = new LinkedList<String>();
                    rowList.add(columnList);

                     for (int column = 1; column <= columnCount; ++column) 
                        {

                            printer.print(resultSet.getString(column));

                        }

                     printer.println(); 

                }
                printer.flush();
                printer.close();


                }

Replace

printer.print(resultSet.getString(column));

with

printer.print(resultSet.getString(column).replace(":", "\":"));

The line breaks are part of your actual data and I would question why they are there in the first place and whether you really should remove them at all. If you are sure that's what you want to do, replace

printer.print(resultSet.getString(column));

with

String s = resultSet.getString(column);
printer.print(s.replaceAll("[\r]\n", ""));

Assuming that you use Apache common-csv package, you could use withEscape and use a suitable escape character for columns containing characters that break the format.

Current versions apply the supplied escape character to LF, CR, delimiter and escape character.

CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT.RFC4180
   .withHeader(resultSet)
   .withQuoteMode(QuoteMode.ALL)
   .withEscape("\\"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM