java - 如何从 Java 中的多个 hashMap 创建多个 .csv 文件?
问题描述
我尝试从几个 hashMap 创建(用数据写入)几个文件。
Map<String, List<CSVRecord>> map = new HashMap<>();
List<CsvStructureEntity> listWithData = new ArrayList<>();
try {
Reader reader = new BufferedReader(new FileReader(file));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT
.withFirstRecordAsHeader()
.withIgnoreHeaderCase()
.withTrim());
for (CSVRecord csvRecord : csvParser) {
LOGGER.info("The parser read line ...");
// Accessing values by Header names
String line1 = csvRecord.get("line1");
String line2 = csvRecord.get("line2");
String lineId = csvRecord.get("lineId");
List<CSVRecord> list = map.getOrDefault(lineId, new LinkedList<CSVRecord>());
list.add(csvRecord);
map.put(lineId, list);
// Write map to new .csv files
String lineSeparator = System.getProperty("line.separator");
try (Writer writer = new FileWriter("/home/tmp/new_csv_file.csv")) {
for (Map.Entry<String, List<CSVRecord>> entry : map.entrySet()) {
writer.append(entry.getKey())
.append(',')
.append(entry.getValue())
.append(lineSeparator);
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
String line3 = csvRecord.get("line3");
String line4 = csvRecord.get("line4");
String line5 = csvRecord.get("line5");
... (and so on until the 43rd line)
我的源文件包含 4 个不同的“lineId”(1、2、3、4)根据我写的内容,所有内容都写入一个文件。我需要将它们全部写入不同的文件(在不同的 4 个文件中),即第一个文件将被写入 lineId = 1 和此 lineId 的所有行,第二个文件后面将是 lineId = 2 和此的所有行lineId 等等。
有人可以说有什么问题吗?谢谢
解决方案
为要写入的每个文件创建新的 FileWriter。因为目前您只创建 1 个文件。
推荐阅读
- javascript - React中过滤列表为空时如何显示消息
- javascript - XSTLProcessor 绕过和标记
- php - 无限循环的长轮询使网站变慢(本地主机)
- azure - 无法在 Azure devops 的 Azsk 任务中更新策略设置
- symfony - Symfony 固定页面上的元素
- java - Android上的TCP套接字连接被拒绝
- python - 如何通过 Python shell 添加具有多个 actie_gebruiker(s) 的新记录?
- ios - Travis 上的 Fastlane 因“请为 /Applications 启用 Spotlight 索引”而失败
- wordpress - 我更改了我的 Wordpress 主题文件夹。现在我改回来后找不到我的样式表
- angular - Angular 6 在使用模态时从另一个组件调用属性时给出错误“TypeError:无法读取属性”