You can easily append to a file in Java with the PrintWriter class. When creating it, simply use the overloaded constructor to tell the PrintWriter to append to the file:
PrintWriter printWriter
= new PrintWriter(new FileWriter(new File("filename"), true));
As for the second part, you can do this by reading everything into a Map and then rewriting it in the format you want.
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]));
}
Now that everything is nice and sorted, you can easily write it out:
// 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();
}
}
That should be it.
** I could have made a mistake, not in front of an IDE at the moment. Please let me know so I can correct it.
** Also, please note this is NOT a robust answer, but one that is very specific to the format of you input file. It has no exception handling which is a bad thing, but you can flesh it out.