0

I am writing a little app where I go to an api, get some json data and fill that into a csv file.

It works so far, that I get a csv file, with the correct rows, but instead of columns there are still commas in text form in file.

I am using opencsv.

private void writeCsv(InputStream input, String name) throws IOException {
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        StringBuilder text = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            text.append(line);
        }
        JSONArray docs = new JSONArray(text.toString());
        File file=new File(name + ".csv");
        String csv = CDL.toString(docs);
        CSVWriter writer = new CSVWriter(new FileWriter(file));
        BufferedReader sreader = new BufferedReader(new StringReader(csv));
        String csvline;
        while ((csvline = sreader.readLine()) != null) {
            writer.writeNext(csvline);
        }
        writer.close();
        System.out.println("done");
}
Ozymandias
  • 199
  • 6
  • 17

1 Answers1

0

You need to add column mapping strategy.

ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();

check this blog for better understanding. http://www.javainterviewpoint.com/csvtobean-and-beantocsv-example-using-opencsv/

Bhavesh
  • 882
  • 2
  • 9
  • 18