I need to write a csv with java, I'm using org.apache.commons, but when printing the file the delimiter ";" appears before each line.
My code
public static Object createCsvFile(JsonArray array, HttpServletResponse response) {
var header = array.get(0).getAsJsonObject().keySet();
try {
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, CSVFormat.newFormat(';'));
csvPrinter.printRecord(header);
for (int i = 0; i < array.size(); i ) {
JsonObject values = array.get(i).getAsJsonObject();
Set<String> keys = values.keySet();
csvPrinter.print("\r\n");
for (String key: keys) {
csvPrinter.printRecord(values.get(key).toString() ";");
}
}
csvPrinter.close();
return stringWriter.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
My result
;4;"11/10/2022 06:10";117;"ENTRADA POR PRODUCAO";422;"LINGUICA DE CARNE SUINA - AURORA - 5KG - CHURRASCO";"MI";"078911644790352718";"0422101011";"10/10/2022";1025;"116-BRASIL - MI";
Note that before the 4 there is a ";"
I tried to use some alternatives that I found in the user guide, but I didn't get anything.
CodePudding user response:
If you remove the ";"
in csvPrinter.printRecord(values.get(key).toString() ";");
, you'll see that it's your CSVPrinter
that add them before each line.
You should let your CSVPrinter
handle the delimiter.
Just to give you some inspiration, try with this :
public static Object createCsvFileBis(JsonArray array, HttpServletResponse response) {
var header = array.get(0).getAsJsonObject().keySet();
try (
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, CSVFormat.newFormat(';'))
) {
csvPrinter.printRecord(header);
for (int i = 0; i < array.size(); i ) {
JsonObject values = array.get(i).getAsJsonObject();
Set<String> keys = values.keySet();
csvPrinter.printRecord("\n");
List<String> row = new ArrayList<>();
for (String key : keys) {
row.add(values.get(key).toString());
}
csvPrinter.printRecord(row);
}
csvPrinter.flush();
return stringWriter.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}