首页 > 解决方案 > 如何从 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 等等。

有人可以说有什么问题吗?谢谢

标签: javacsvcollectionshashmap

解决方案


为要写入的每个文件创建新的 FileWriter。因为目前您只创建 1 个文件。


推荐阅读