重新格式化CSV输入文件

时间:2010-11-09 16:57:17

标签: java csv arraylist

我想要做的只是最初创建CSV文件并在每个月末追加到它。以便按以下格式生成年度CSV文件:

第1个月,Nokia8800,156.0
第1个月,诺基亚3120,113.0 第2个月,Nokia8800,16.0 第2个月,诺基亚3120,152.0
第3个月,Nokia8800,44.0
第3个月,诺基亚3120,52.0等12个月。

现在我需要的是以下列文件格式重新格式化此CSV: 第1,2,3,4,5,6,7,8,9,10,11,12个月 Nokia8800,156.0,16.0,44.0
诺基亚3120,113.0,152.0,52.0等12个月。

我怎样才能完成这项工作?

提前感谢。

*希望这可以通过arraylist解决..

3 个答案:

答案 0 :(得分:1)

最佳解决方案是使用ListMap

由于您只有12个月,因此您可以创建List并添加12个项目,每月1个。

对于其中每个项目,您可以创建一个Map<String, Double>,其中键是项目的名称,double是该月份该项目的值。

当您需要输出年度报告时,您可以在第一个月内循环浏览每个项目,并从其他每个地图中提取该项目的值。

它看起来像这样:

List<Map<String, Double>> list = new ArrayList<Map<String, Double>>();
for(int i = 0; i < 12; i++)
    list.add(new HashMap<String, Double>());

for(Entry <String, Double> entry : list.get(0).entrySet())
{
    String row = entry.getKey() + "," + entry.getValue().toString();
    for(Map<String, Double> map : list.subList(1, list.size()))
    {
        row += map.get(entry.getKey()).toString();
    }
}

答案 1 :(得分:1)

您可以使用PrintWriter类轻松附加到Java文件中。创建它时,只需使用重载的构造函数告诉PrintWriter追加到文件:

PrintWriter printWriter
    = new PrintWriter(new FileWriter(new File("filename"), true));

至于第二部分,您可以通过将所有内容读入Map中,然后以您想要的格式重写它。

Map<String, ArrayList<Double>> REGISTRY = new HashMap<String, ArrayList<Double>>();
REGISTRY.add("Month", new ArrayList<Double>());

Scanner scanner = new Scanner(new File("filename"));
while (scanner.hashNextLine()) {
    String[] line = scanner.nextLine().split(",");

    // for the month key
    String month = line[0].split(" ")[1];
    REGISTRY.get("Month").add(new Double(month));

    // then for the rest of the entries
    if (!REGISTRY.containsKey(line[1])) {
        REGISTRY.add(line[1], new ArrayList<Double>());
    }
    REGISTRY.get(line[1]).add(new Double(line[2]));
}

现在一切都很好并且排序好了,你可以轻松地写出来:

// first the months
printWriter2.print("Month");
for (Double d : REGISTRY.get("Month")) {
    printWriter2.print("," + d);
}
printWriter2.println();

// now the rest
for (Map.Entry<String, ArrayList<Double>> tuple : REGISTRY.entrySet()) {
    if (!tuple.getKey().equals("Month")) {
        printWriter2.print(tuple.getKey());
        for (Double d : tuple.getValue()) {
            printWriter2.print("," + d);
        }
        printWriter2.println();
    }
}

应该是它。

**我本可以犯错,而不是在IDE前面。请让我知道,以便我能纠正。

**另外,请注意这不是一个强有力的答案,而是一个非常特定于您输入文件格式的答案。它没有异常处理这是一件坏事,但你可以充实它。

答案 2 :(得分:0)

只需逐行阅读,将其拆分为,并将其存储在列表&gt;中。 当你阅读它之后,只需遍历列表并仅仅修改第一个项目。然后再做第二次,依此类推。这样你就可以按照自己的意愿'转变'你的csv。

相关问题