重新格式化 CSV 输入文件
我想做的只是最初创建 CSV 文件并在每个月末附加到它。从而生成以下格式的年度CSV文件:
Month 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个月。
我怎样才能完成这件事?
提前致谢。
*希望这可以通过数组列表来解决..
what I want to do is just create CSV file initially and append to it every month end. So as to generate annual CSV file in following format:
Month 1, Nokia8800, 156.0
Month 1, Nokia3120, 113.0
Month 2, Nokia8800, 16.0
Month 2, Nokia3120, 152.0
Month 3, Nokia8800, 44.0
Month 3, Nokia3120, 52.0 and so on for 12 months.
Now what i need is to re-format this CSV in following file format:
Month 1,2,3,4,5,6,7,8,9,10,11,12
Nokia8800,156.0,16.0,44.0
Nokia3120, 113.0,152.0,52.0 and so on for 12 months.
How can i get this done?
thanks in advance.
*hope this can be solve with an arraylist..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 PrintWriter 类轻松附加到 Java 中的文件。创建它时,只需使用重载的构造函数告诉 PrintWriter 追加到文件中:
至于第二部分,您可以通过将所有内容读入 Map 中,然后以您想要的格式重写来完成此操作。
现在一切都很好并且已排序,您可以轻松地写出来:
应该是这样。
** 我可能会犯一个错误,而不是在 IDE 面前。请让我知道,以便我纠正它。
** 另外,请注意,这不是一个可靠的答案,而是一个非常特定于您输入文件格式的答案。它没有异常处理,这是一件坏事,但你可以充实它。
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:
As for the second part, you can do this by reading everything into a Map and then rewriting it in the format you want.
Now that everything is nice and sorted, you can easily write it out:
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.
最好的解决方案是使用
List
和Map
。由于您只有 12 个月,因此您可以创建一个
List
并向其中添加 12 项,每个月 1 项。对于其中每个项目,您都可以创建一个
Map
,其中键是项目的名称,双精度数是该项目当月的值。当您需要输出年度报告时,您可以循环遍历第一个月中的每个项目,并从其他每个映射中提取该键的值。
它看起来像这样:
The best solution for this would be to use a
List
and aMap
.Since you only have 12 months, you can create a
List
and add 12 items to it, 1 for each month.For each of these items, you can create a
Map<String, Double>
where the key is the name of the item and the double is your value for that item for that month.When you need to output the annual report, you can then loop through each item in the first month, and pull the value for that key from each of the other maps.
It would look something like this:
只需逐行读取它,用
,
分割并将其存储在 List> 中。当您阅读完它后,只需迭代列表并仅提取第一项。然后再做第二次,依此类推。这样你就可以按照你的意愿“转动”你的csv。
Just read it line by line, split it by the
,
and store it in a List>.When you have read it, just iterate over the list and only pring the first item. then do it again for the second and so on. this way you 'turn' your csv as you wished.