Home » Java » java – how to add the comma in a string to a single cell in csv-Exceptionshub

java – how to add the comma in a string to a single cell in csv-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

while i was trying to write some text to a CSV, I found out that it cut the text at the first comma in the text and thus writing the string to 2 different cell instead of 1. is there anyway around this issue as the text will be crawled from the web instead of input

the gist of the function code is

String text = "hello, this is me";
        try {
            PrintWriter csv = new PrintWriter(new File("test.csv"));
            csv.write(text);        
            csv.close();        
        }
        catch(Exception e) {

        }
How to&Answers:

test.csv

a;b;c
d;e;f

test2.csv

a;b;c
,;e;f

Java code using opencsv:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.CSVWriter;

public class Sof {

    public static void main(String[] args) {
        CSVReader reader;
        try (CSVWriter writer = new CSVWriter(new FileWriter(new File("src/main/resources/test2.csv")), ';', Character.MIN_VALUE, '\', "\n");) {
            reader = new CSVReaderBuilder(new InputStreamReader(new FileInputStream("src/main/resources/test.csv"), StandardCharsets.UTF_8))
                    .withCSVParser(new CSVParserBuilder().withSeparator(';').build()).build();
            final List<String[]> csvBody = reader.readAll();
            System.out.println(csvBody.size());
            csvBody.get(1)[0] = ",";
            writer.writeAll(csvBody);
            writer.flush();
            reader.close();
        } catch (final IOException e1) {
            System.err.println(e1);
        }

    }

}