写入 csv 文件时有时双引号会消失

Sometime double quotes disappear when write to csv file

我正在将我的数据写入 java 中的 csv 文件。下面是我的代码

    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");
    }

当我检查我的结果文件时,最后一行在 accountName test3 和 test4 中没有“”。

accountId,accountName,address
1111,"test1111111",england
2222,"test222222222",tokyo
3333,test3,italy
4444,test4,indo

这是我的输入列表:

[{accountId=1111, accountName=test1111111, address=england}, {accountId=2222, 
accountName=test222222222, address=tokyo}, {accountId=3333, accountName=test3, 
address=italy}, {accountId=4444, accountName=test4, 
address=indo}]

这是我读取 csv 文件并将其分配给列表的代码:

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;
}

我的代码有什么错误?

看来你是对的,String长的时候加引号。 因此,为避免不一致,您可以指定是否需要引号或不使用 CsvGenerator.Feature.ALWAYS_QUOTE_STRINGSCsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING

这将始终添加双引号:

CsvMapper mapper = new CsvMapper();
mapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);
mapper.writer(schema).writeValues(writer).writeAll(list);

另一个永远不要加双引号