Java - 将哈希映射写入 csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31172003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Write hashmap to a csv file
提问by activelearner
I have a hashmap with a String key and String value. It contains a large number of keys and their respective values.
我有一个带有字符串键和字符串值的哈希图。它包含大量的键和它们各自的值。
For example:
例如:
key | value
abc | aabbcc
def | ddeeff
I would like to write this hashmap to a csv file such that my csv file contains rows as below:
我想将此哈希图写入 csv 文件,以便我的 csv 文件包含如下行:
abc,aabbcc
def,ddeeff
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.
我在这里使用 supercsv 库尝试了以下示例:http://javafascination.blogspot.com/2009/07/csv-write-using-java.html 。但是,在此示例中,您必须为要添加到 csv 文件的每一行创建一个哈希图。我有大量的键值对,这意味着需要创建多个哈希图,每个哈希图都包含一行的数据。我想知道是否有更优化的方法可用于此用例。
Thanks in advance!
提前致谢!
采纳答案by James Bassett
As your question is asking how to do this using Super CSV, I thought I'd chime in (as a maintainer of the project).
由于您的问题是询问如何使用 Super CSV 做到这一点,我想我会插话(作为项目的维护者)。
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.
我最初认为您可以使用CsvBeanWriter
和 的名称映射数组迭代映射的条目集"key", "value"
,但这不起作用,因为HashMap
的内部实现不允许反射来获取键/值。
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!):
所以你唯一的选择是使用CsvListWriter
如下。至少这样你就不必担心转义 CSV(这里的每个其他例子都只是用逗号连接......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);
}
Output:
输出:
abc,aabbcc
def,ddeeff
回答by Sean Bright
Something like this should do the trick:
像这样的事情应该可以解决问题:
String eol = System.getProperty("line.separator");
try (Writer writer = new FileWriter("somefile.csv")) {
for (Map.Entry<String, String> entry : myHashMap.entrySet()) {
writer.append(entry.getKey())
.append(',')
.append(entry.getValue())
.append(eol);
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
回答by dognose
If you have a single hashmap it is just a few lines of code. Something like this:
如果你有一个单一的哈希图,它只是几行代码。像这样的东西:
Map<String,String> myMap = new HashMap<>();
myMap.put("foo", "bar");
myMap.put("baz", "foobar");
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> kvp : myMap.entrySet()) {
builder.append(kvp.getKey());
builder.append(",");
builder.append(kvp.getValue());
builder.append("\r\n");
}
String content = builder.toString().trim();
System.out.println(content);
//use your prefered method to write content to a file - for example Apache FileUtils.writeStringToFile(...) instead of syso.
result would be
结果将是
foo,bar
baz,foobar
回答by James
My Java is a little limited but couldn't you just loop over the HashMap and add each entry to a string?
我的 Java 有点受限,但您不能循环遍历 HashMap 并将每个条目添加到字符串中吗?
// m = your HashMap
StringBuilder builder = new StringBuilder();
for(Entry<String, String> e : m.entrySet())
{
String key = e.getKey();
String value = e.getValue();
builder.append(key);
builder.append(',');
builder.append(value);
builder.append(System.getProperty("line.separator"));
}
string result = builder.toString();
回答by Ajay Kumar
Using the Hymanson API, Map or List of Map could be written in CSV file. See complete example here
使用 Hymanson API,可以将地图或地图列表写入 CSV 文件。在此处查看完整示例
/**
* @param listOfMap
* @param writer
* @throws IOException
*/
public static void csvWriter(List<HashMap<String, String>> listOfMap, Writer writer) throws IOException {
CsvSchema schema = null;
CsvSchema.Builder schemaBuilder = CsvSchema.builder();
if (listOfMap != null && !listOfMap.isEmpty()) {
for (String col : listOfMap.get(0).keySet()) {
schemaBuilder.addColumn(col);
}
schema = schemaBuilder.build().withLineSeparator(System.lineSeparator()).withHeader();
}
CsvMapper mapper = new CsvMapper();
mapper.writer(schema).writeValues(writer).writeAll(listOfMap);
writer.flush();
}