如何从Java中的多个hashMap创建多个.csv文件?

时间:2018-10-01 10:23:21

标签: java csv collections hashmap

我尝试从多个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等。

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

1 个答案:

答案 0 :(得分:0)

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

相关问题