I am writing my data to csv file in java. Below is my code
public static void writeAccountToFile(List<Map<String, Object>> list, String filePath) {
System.out.println("Write data to csv file start");
try {
File file = new File(filePath);
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
CsvSchema schema = null;
CsvSchema.Builder schemaBuilder = CsvSchema.builder();
if (list != null && !list.isEmpty()) {
for (String col : list.get(0).keySet()) {
schemaBuilder.addColumn(col);
}
schema = schemaBuilder.build().withLineSeparator("\r").withHeader();
}
CsvMapper mapper = new CsvMapper();
mapper.writer(schema).writeValues(writer).writeAll(list);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Write data to csv file end");
}
When I check my result file, last line there is no "" in accountName test3 and test4.
accountId,accountName,address
1111,"test1111111",england
2222,"test222222222",tokyo
3333,test3,italy
4444,test4,indo
Here is my input list:
[{accountId=1111, accountName=test1111111, address=england}, {accountId=2222,
accountName=test222222222, address=tokyo}, {accountId=3333, accountName=test3,
address=italy}, {accountId=4444, accountName=test4,
address=indo}]
Here is my code to read csv file and assign it to list:
public static List<Map<String, Object>> loadFileAccount(String filePath) throws Exception {
List<Map<String, Object>> list = new ArrayList<>();
removeBom(Paths.get(filePath));
System.out.println("Load account data from csv start");
File file = new File(filePath);
Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
Iterator<Map<String, Object>> iterator = new CsvMapper()
.readerFor(Map.class)
.with(CsvSchema.emptySchema().withHeader())
.readValues(reader);
while (iterator.hasNext()) {
Map<String, Object> keyVals = iterator.next();
list.add(keyVals);
}
reader.close();
System.out.println("Load account data from csv end");
return list;
}
What is error in my code?
CodePudding user response:
It seems that you are right, when the String is long, it adds quotes.
So to avoid inconsistencies, you can specify if you want quotes or not using
CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS
or CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING
This will always add double quotes:
CsvMapper mapper = new CsvMapper();
mapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);
mapper.writer(schema).writeValues(writer).writeAll(list);
The other one should never add double quotes