1. Introduction
1.导言
Comma-separated value (CSV) files are easy to work with and applicable in various applications regarding data storing and exchanging. Java developers, at some point, have to export data to CSVs when handling data structures like HashMaps.
逗号分隔值 (CSV) 文件易于使用,适用于有关数据存储和交换的各种应用程序。Java 开发人员在处理 HashMaps 等数据结构时,有时必须将数据导出为 CSV。
In this tutorial, we’ll learn how to write HashMap to a CSV file.
在本教程中,我们将学习如何将 HashMap 写入 CSV 文件。
2. Writing HashMap to CSV Manually
2.将 HashMap 手动写入 CSV
To write data into the “employee_data.csv” file, we’ll use the help of the FileWriter class. Afterward, each row of employee data is inserted into separate EmployeeData cells. Here’s the code that accomplishes this:
要将数据写入”employee_data.csv“文件,我们将使用 FileWriter 类的帮助。随后,每一行员工数据都将插入到单独的 EmployeeData 单元格中。以下是实现这一目标的代码:
Map<String, String> employeeData = new HashMap<>();
employeeData.put("Name", "John Doe");
employeeData.put("Title", "Software Engineer");
employeeData.put("Department", "Engineering");
employeeData.put("Salary", "75000");
try (FileWriter csvWriter = new FileWriter("employee_data.csv")) {
// Write header row
csvWriter.append("Name,Title,Department,Salary\n");
// Write data row
csvWriter.append(employeeData.get("Name")).append(",");
csvWriter.append(employeeData.get("Title")).append(",");
csvWriter.append(employeeData.get("Department")).append(",");
csvWriter.append(employeeData.get("Salary")).append("\n");
// Close the csvWriter to save the data
csvWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
In the above code, we created row headers and then traversed the employeeData Hashmap to append each key value as a CSV row delimited by a comma. After completing the data write operation, we close the csvWriter to save the data. And then, finally, the code tries to handle exceptions.
在上述代码中,我们创建了行标题,然后遍历 employeeData Hashmap 将每个键值追加为以逗号分隔的 CSV 行。最后,代码会尝试处理异常。
3. Writing HashMap to CSV Using Apache Commons CSV
3.使用 Apache Commons CSV 将 HashMap 写入 CSV
Working with CSV files in Java is a robust and efficient endeavor using the Apache Commons CSV library. To write HashMap data to a CSV file, we should first add the following dependency to our project’s pom.xml file:
使用 Apache Commons CSV 库在 Java 中处理 CSV 文件是一项强大而高效的工作。要将 HashMap 数据写入 CSV 文件,我们应首先在项目的 pom.xml 文件中添加以下依赖关系:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.10.0</version>
</dependency>
Now, let’s see how to retrieve data from a CSV using the Apache Commons library:
现在,让我们看看如何使用 Apache Commons 库从 CSV 中检索数据:
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter("employee_data2.csv"), CSVFormat.DEFAULT)) {
// Write header row
csvPrinter.printRecord("Name", "Title", "Department", "Salary");
// Write data row
csvPrinter.printRecord(employeeData.get("Name"), employeeData.get("Title"), employeeData.get("Department"), employeeData.get("Salary"));
} catch (IOException e) {
e.printStackTrace();
}
// Ensure the CSV file exists
assertTrue(new File("employee_data2.csv").exists());
In the above code, we initialize a CSVPrinter and create a new FileWriter object to identify where the output CSV file is expected. Subsequently, we iterate through the HashMap using the CSVPrinter to put its content into the CSV file. Lastly, we close both CSVPrinter and FileWriter to ensure that the data is properly flushed and saved as required.
在上述代码中,我们初始化了一个 CSVPrinter 并创建了一个新的 FileWriter 对象,以确定输出 CSV 文件的位置。随后,我们使用 CSVPrinter 遍历 HashMap 并将其内容放入 CSV 文件。最后,我们关闭 CSVPrinter 和 FileWriter 以确保数据按要求正确刷新和保存。
4. Conclusion
4.结论
In conclusion, we have learned that it is possible for us to generate and write HashMap into a CSV File by means of assertion while asserting the proof of our implementation in Java.
总之,我们已经了解到,我们可以通过断言生成 HashMap 并将其写入 CSV 文件,同时断言证明我们在 Java 中的实现。
To be specific, this skill is used in various data-related activities like transferring data towards more detailed analyses, report creation, and migration.
具体来说,这项技能可用于各种与数据相关的活动,如将数据转入更详细的分析、创建报告和迁移。
As always, the complete code samples for this article can be found over on GitHub.
与往常一样,本文的完整代码示例可在 GitHub 上找到。