我想要做的只是最初创建 CSV 文件并在每个月末附加到它。从而生成以下格式的年度CSV文件:
第 1 个月,Nokia8800,156.0
第 1 个月,Nokia3120,113.0
第 2 个月,Nokia8800,16.0
第 2 个月,Nokia3120,152.0
第三个月,Nokia8800,44.0
3月份,Nokia3120,52.0等12个月。
现在我需要将这个 CSV 重新格式化为以下文件格式:
月份 1,2,3,4,5,6,7,8,9,10,11,12
诺基亚8800,156.0,16.0,44.0
Nokia3120、113.0、152.0、52.0等12个月。
我怎样才能完成这个工作?
提前致谢。
*希望这可以通过数组列表来解决..
最佳答案
您可以使用 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 面前。请让我知道,以便我纠正它。
** 另外,请注意,这不是一个可靠的答案,而是一个非常特定于您输入文件格式的答案。它没有异常处理,这是一件坏事,但你可以充实它。
关于java - 重新格式化 CSV 输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4136299/