我有一个带有String键和String值的hashmap。它包含大量的键及其各自的值。
例如:
key | value
abc | aabbcc
def | ddeeff
我想将此hashmap写入csv文件,以便我的csv文件包含如下行:
abc,aabbcc
def,ddeeff
我在这里使用supercsv库尝试了以下示例:http://javafascination.blogspot.com/2009/07/csv-write-using-java.html。但是,在此示例中,您必须为要添加到csv文件的每一行创建一个hashmap。我有大量的键值对,这意味着需要创建几个哈希映射,每个哈希映射包含一行的数据。我想知道是否有更优化的方法可用于此用例。
提前致谢!
答案 0 :(得分:5)
使用Jackson API,Map或Map List可以用CSV文件编写。请参阅完整示例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();
}
答案 1 :(得分:3)
这样的事情可以解决问题:
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);
}
答案 2 :(得分:3)
当你的问题是询问如何使用Super CSV进行此操作时,我想我会参与其中(作为项目的维护者)。
我最初认为您可以使用CsvBeanWriter
和"key", "value"
的名称映射数组迭代地图的条目集,但这不起作用,因为HashMap
的内部实现没有不允许反射获得键/值。
因此,您唯一的选择是使用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);
}
输出:
abc,aabbcc
def,ddeeff
答案 3 :(得分:0)
如果你有一个hashmap,那只是几行代码。像这样:
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.
结果将是
foo,bar
baz,foobar
答案 4 :(得分:0)
我的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();
答案 5 :(得分:0)
Map<String, String> csvMap = new TreeMap<>();
csvMap.put("Hotel Name", hotelDetails.getHotelName());
csvMap.put("Hotel Classification", hotelDetails.getClassOfHotel());
csvMap.put("Number of Rooms", hotelDetails.getNumberOfRooms());
csvMap.put("Hotel Address", hotelDetails.getAddress());
// specified by filepath
File file = new File(fileLocation + hotelDetails.getHotelName() + ".csv");
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
String[] header = csvMap.keySet().toArray(new String[csvMap.size()]);
String[] dataSet = csvMap.values().toArray(new String[csvMap.size()]);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
// adding data to csv
writer.writeNext(header);
writer.writeNext(dataSet);
// closing writer connection
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}