gpt4 book ai didi

java - 用逗号分隔 HashMap 输出到 .csv

转载 作者:行者123 更新时间:2023-11-30 06:46:04 26 4
gpt4 key购买 nike

在此程序中,我将数据从 HashMap 数据库导出到 .csv。写入文件的数据是key和studentInformation,它由Name、Major和GPA组成。该代码将其输出到 .csv 很好,但是我希望每个值都用逗号分隔,以便每个值位于电子表格的不同列中。我将如何在数据库的每个输出上实现逗号???提前致谢。

      //Output the database to the file
Map.Entry<Integer, Student> studentInformation = iterator.next();
int key = studentInformation.getKey();
bW.write("Student ID: " + key + (",") + studentInformation.getValue() + ("\n\n");

如果我在studentInformation.getValue()之后添加+(“,”),它不会分隔studentInformation的每个值...有什么想法吗?

最佳答案

您想要在 CSV 列中使用的每个字段都必须从 Student 类中单独检索。
例如:

  public static final String CSV_SEPARATOR  = ",";
...
Map.Entry<Integer, Student> studentEntry = iterator.next();
int key = studentEntry.getKey();
Student student = studentEntry.getValue();
String line = "Student ID: " + key + CSV_SEPARATOR + student.getName()
+ CSV_SEPARATOR + student.getMajor() + System.lineSeparator();
bW.write(line);

使用自定义常量作为 CSV_SEPARATOR 以避免重复“,”并且更喜欢 System.lineSeparator()\n\n 取决于操作系统。

最后为什么要重新发明轮子?SuperCSV 和 OpenCSV 等库做得非常好。
您应该尝试其中之一。

关于java - 用逗号分隔 HashMap 输出到 .csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com