【问题标题】:How to create several .csv files from several hashMap in Java?如何从 Java 中的多个 hashMap 创建多个 .csv 文件?
【发布时间】:2018-10-01 10:23:20
【问题描述】:

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

有人可以说什么是错的吗? 谢谢

【问题讨论】:

  • 抱歉,您希望我们在这里告诉您什么?如果您的输入数据需要转到不同的输出文件,那么只需编写代码,A) 检查输入,然后 B) 将其分派到适当的目标。你到底有什么问题?
  • @GhostCat 我的问题是数据写入一个文件,但我需要将数据写入不同的文件。我不明白为什么将数据写入一个文件。
  • 您显示的代码...显示了您如何写入一个特定文件?!那你还期待什么? --> 请阅读minimal reproducible example 并相应地增强您的问题。

标签: java csv collections hashmap


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多