如何将 CSV 记录映射到 bean?

发布于 2025-01-03 13:54:51 字数 649 浏览 2 评论 0原文

我正在寻找一个 Java 库,它可以帮助我解析包含管道分隔记录的 CSV 文件,并从中创建我的 bean 类的实例。

我研究了几种替代方案,例如 SuperCSV、OpenCSV、BeanIO、JFileHelper、jsefa,...但它们似乎都不具备所需的功能。

库的要求:

  1. 支持具有可变数量字段的记录,
  2. 提供迭代器式访问,因此文件永远不会完全加载到内存中,
  3. 支持将字段映射到其实际类型,即能够获取日期字段并将其放入 java.util.Date 中。 util.Date 到我的 bean 而不是字符串中
  4. 让我提供我自己的工厂对象来创建 bean,而不是默认为 Class.newInstance()

我研究过的所有库似乎都缺少要求#4。

我可以忍受反射,但问题是它仍然为 CSV 文件中的每一行创建一个新的 bean 对象。由于此时我想要对 bean 执行的唯一操作是将其传递到持久层并将其存储在数据库中,因此将几个 bean 实例放入池中并创建一个从中获取实例的工厂是有意义的这个泳池。这样我就可以重复使用我的实例,并且解析 100000 行 CSV 文件不会导致内存中存在 100000 个实例,直到 GC 出现为止。

有谁知道有一个图书馆可以满足所有这些要求?

I'm looking for a Java library that can help me parse a CSV file containing pipe-delimited records and create instances of my bean class from them.

I've looked into several alternatives such as SuperCSV, OpenCSV, BeanIO, JFileHelper, jsefa, ... but neither of them seems to have what it takes.

Requirements of the library:

  1. support records with a variable number of fields
  2. provide iterator-style access so the file is never loaded entirely into memory
  3. support mapping a field to its actual type, i.e. be able to take an date field and put it a java.util.Date into my bean instead of a string
  4. let me supply my own factory object to create the beans from, instead of defaulting to Class.newInstance()

All the libraries I've looked into seem to lack requirement #4.

I can live with reflection, but the problem is that it still creates a new bean object for every line in the CSV file. Since the only thing I want to do with my bean at this point is pass it to my persistence layer and store it in the DB, it makes sense to put a couple of the bean instances into a pool and create a factory that takes instances from this pool. This way I can re-use my instances and parsing a 100000 line CSV file won't result in 100000 instances living in memory until the GC comes along.

Does anyone know of a library that can handle all these requirements?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

今天小雨转甜 2025-01-10 13:54:51

这可能是一个替代方案: https://github.com/org-tigris-jsapar/jsapar< /a>
但它可能达不到要求#4。

在这里,您可以找到更全面的替代方案列表:https://org-tigris- jsapar.github.io/jsapar/links

编辑
从 jsapar 版本 1.8 开始,现在可以在外部工厂类中自定义 Java 对象创建,因此我猜现在也满足了要求#4。

This might be an alternative: https://github.com/org-tigris-jsapar/jsapar
It will probably fall short on requirement #4 though.

Here, you can find a more comprehensive list of alternatives: https://org-tigris-jsapar.github.io/jsapar/links

EDIT
As of jsapar version 1.8, it is now possible to customize Java object creation in an external factory class so I guess that requirement #4 is now also complied to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文