Java CSV 文件操作
我有以下示例 CSV 文件,
rc,u,s,ui,gh
m,1,8,0,12
n,3,0,0,7
d,1,1,8,0
我想读取此 CSV 文件并按其名称(例如 s)获取列。将获取的列减去一些值并更新 CSV 文件中的该列。
有没有一种简单的方法可以用Java实现呢?
I have following sample CSV file
rc,u,s,ui,gh
m,1,8,0,12
n,3,0,0,7
d,1,1,8,0
I want to read this CSV file and get column by its name (e.g., s). subtract fetched column by some values and update that column in the CSV file.
Is there an easy way to do it in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 PHP 中这很容易,您可以使用 fgetcsv 函数 http://php.net/manual /en/function.fgetcsv.php
添加示例
It is quite easy in PHP, you can use fgetcsv function http://php.net/manual/en/function.fgetcsv.php
Added Sample
这样你就可以获得逗号分隔的令牌。对它们执行您想要的操作,然后查看 BufferedWriter 类来存储值。
This way you can get your comma separated tokens. Do what you want with them and then, have a look at BufferedWriter class to store back the values.
据我所知,没有“简单”的方法可以做到这一点,至少使用标准 Java API 是这样。循环可能是这里唯一的选择。
然而,还有其他语言可以使这种事情相对简单。 R(免费且开源)是一种出色的数据操作语言。
As far as I know, there is no 'easy' way of doing this, at least with the standard Java API. Looping is probably going to be the only option here.
There are, however, other languages which make this kind of thing relatively simple. R (freely available and open source) is a great language for data manipulation.
在 PHP 中,您可以尝试这样的操作:
我放置了两个文件(file.csv 和 file2.csv)来查看更新结果。
我看到你将答案更改为仅java,但我希望这可以帮助你。
In PHP you could try with something like this:
I put two files (file.csv and file2.csv) to see the update results.
I see you change the answer to only java, but I hope this can be help you.
您可以使用 JEzCSV 来读取或写入 CSV 文件,可以读取代码,是开源的
You can use JEzCSV for read or write CSV file, can you can read the code, is open source
您可能对我发布到 GitHub 的代码感兴趣,该代码读取 CSV,将 CSV 放入 POJO,然后从 POJO 写入 CSV 文件。这将使用 POJO 修改原始 CSV,并将所需的新列写入新的 CSV 文件。
https://github.com/Blue4570/CsvAppender
公共类 CsvWriter {
}
You may be interested in the code I have posted to GitHub which reads CSV, puts the CSV into a POJO, and then writes from the POJO to a CSV file. This modifies the original CSV using the POJO and writes the new columns you need to a new CSV file.
https://github.com/Blue4570/CsvAppender
public class CsvWriter {
}