Java - Write hashmap to a csv file

感情迁移 提交于 2019-11-28 02:03:20

As your question is asking how to do this using Super CSV, I thought I'd chime in (as a maintainer of the project).

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.

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

Output:

abc,aabbcc
def,ddeeff

Using the Jackson API, Map or List of Map could be written in CSV file. See complete example here

 /**
 * @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();
}

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

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

My Java is a little limited but couldn't you just loop over the HashMap and add each entry to a string?

// 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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!