您可以使用 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 面前。请告诉我,以便我更正。
** 另外,请注意这不是一个可靠的答案,而是一个非常特定于您输入文件格式的答案。它没有异常处理,这是一件坏事,但你可以充实它。