Java - 将哈希图写入 csv 文件 [英] Java - Write hashmap to a csv file
问题描述
我有一个带有字符串键和字符串值的哈希图.它包含大量的键和它们各自的值.
I have a hashmap with a String key and String value. It contains a large number of keys and their respective values.
例如:
key | value
abc | aabbcc
def | ddeeff
我想将此哈希图写入 csv 文件,以便我的 csv 文件包含如下行:
I would like to write this hashmap to a csv file such that my csv file contains rows as below:
abc,aabbcc
def,ddeeff
我在这里使用 supercsv 库尝试了以下示例:http://javafascination.blogspot.com/2009/07/csv-write-using-java.html.但是,在此示例中,您必须为要添加到 csv 文件的每一行创建一个 hashmap.我有大量的键值对,这意味着需要创建几个哈希图,每个哈希图都包含一行的数据.我想知道是否有更优化的方法可用于此用例.
I tried the following example here using the supercsv library: http://javafascination.blogspot.com/2009/07/csv-write-using-java.html. However, in this example, you have to create a hashmap for each row that you want to add to your csv file. I have a large number of key value pairs which means that several hashmaps, with each containing data for one row need to be created. I would like to know if there is a more optimized approach that can be used for this use case.
推荐答案
当您的问题是如何使用 Super CSV 执行此操作时,我想我会加入(作为项目的维护者).
As your question is asking how to do this using Super CSV, I thought I'd chime in (as a maintainer of the project).
我最初以为您可以使用 CsvBeanWriter
和 "key", "value"
的名称映射数组来迭代映射的条目集,但这并没有工作,因为 HashMap
的内部实现不允许反射来获取键/值.
I initially thought you could just iterate over the map's entry set using CsvBeanWriter
and a name mapping array of "key", "value"
, but this doesn't work because HashMap
's internal implementation doesn't allow reflection to get the key/value.
所以你唯一的选择是使用 CsvListWriter
如下.至少这样您就不必担心转义 CSV(这里的每个其他示例都只是用逗号连接...aaarrggh!):
So your only option is to use CsvListWriter
as follows. At least this way you don't have to worry about escaping CSV (every other example here just joins with commas...aaarrggh!):
@Test
public void writeHashMapToCsv() throws Exception {
Map<String, String> map = new HashMap<>();
map.put("abc", "aabbcc");
map.put("def", "ddeeff");
StringWriter output = new StringWriter();
try (ICsvListWriter listWriter = new CsvListWriter(output,
CsvPreference.STANDARD_PREFERENCE)){
for (Map.Entry<String, String> entry : map.entrySet()){
listWriter.write(entry.getKey(), entry.getValue());
}
}
System.out.println(output);
}
输出:
abc,aabbcc
def,ddeeff
这篇关于Java - 将哈希图写入 csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!