I've got a file from a vendor that has 115 fixed-width fields per line. What's the best way of parsing that file into the 115 fields so I can use them in my code?
My first thought is just to make constants for each field like NAME_START_POSITION
and NAME_LENGTH
and using substring
. That just seems ugly so I'm curious if there's any other recommended ways of doing this. None of the couple of libraries a Google search turned up seemed any better either. Thanks
Here is the plain java code to read fixedwidth file:
I would use a flat file parser like flatworm instead of reinventing the wheel: it has a clean API, is simple to use, has decent error handling and a simple file format descriptor. Another option is jFFP but I prefer the first one.
uniVocity-parsers comes with a
FixedWidthParser
andFixedWidthWriter
the can support tricky fixed-width formats, including lines with different fields, paddings, etc.Here are a few examples for parsing all sorts of fixed-width inputs.
And here are some other examples for writing in general and other fixed-width examples specific to the fixed-width format.
Disclosure: I'm the author of this library, it's open-source and free (Apache 2.0 License)
Most suitable for Scala, but probably you could use it in Java
I was so fed up with the fact that there is no proper library for fixed length format that I have created my own. You can check it out here: https://github.com/atais/Fixed-Length
A basic usage is that you create a case class and it's described as an
HList
(Shapeless):And you can easily decode your lines now or encode your object: