2010-11-09 132 views
0

我想要做的就是最初创建CSV文件并在每个月末追加到它。以便产生在以下格式年度CSV文件:重新格式化CSV输入文件

月1,Nokia8800,156.0
第1个月,Nokia3120,113.0
第2个月,Nokia8800,16.0
第2个月,Nokia3120,152.0
第3个月,诺基亚8800,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解决..

回答

1

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

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

至于第二部分,你可以通过阅读一切都变成地图,然后在格式重写它这样做,你想。

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之前。请让我知道,所以我可以纠正它。

**另外,请注意,这不是一个健壮的答案,但它是非常具体的输入文件的格式。它没有异常处理,这是一件坏事,但你可以充实它。

0

一行行刚读它,由,拆分,并将其存放在一个List>。 当你阅读它时,只需遍历列表并只读取第一个项目。然后再做第二次,等等。这样你就可以“转”你的csv,只要你愿意。

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(); 
    } 
}