Java fixed-width file format read/write library

TyC picture TyC · Dec 29, 2011 · Viewed 13.2k times · Source

I'm looking for a good Java library that easily allows the read/write of fixed-width files. Needed for maintaining legacy systems, i.e. files are needed to work with COBOL.

Any suggestions are greatly appreciated!

Thanks.

Answer

Jeronimo Backes picture Jeronimo Backes · Nov 23, 2014

uniVocity-parsers parses/writes Fixed-Width inputs (as well as CSV and TSV). It has quite a lot of features you which could use.

Sample input:

YearMake_Model___________________________________Description_____________________________Price___
1997Ford_E350____________________________________ac, abs, moon___________________________3000.00_
1999ChevyVenture "Extended Edition"______________________________________________________4900.00_
1996Jeep_Grand Cherokee__________________________MUST SELL!
air, moon roof, loaded_______4799.00_
1999ChevyVenture "Extended Edition, Very Large"__________________________________________5000.00_
_________Venture "Extended Edition"______________________________________________________4900.00_

Code to read:

FixedWidthFieldLengths lengths = new FixedWidthFieldLengths(4, 5, 40, 40, 8);
FixedWidthParserSettings settings = new FixedWidthParserSettings(lengths);
//sets the character used for padding unwritten spaces in the file
settings.getFormat().setPadding('_');

// creates a fixed-width parser with the given settings
FixedWidthParser parser = new FixedWidthParser(settings);
// parses all rows in one go.
List<String[]> allRows = parser.parseAll(new FileReader(yourFile));

Output:

[Year, Make, Model, Description, Price]
[1997, Ford, E350, ac, abs, moon, 3000.00]
[1999, Chevy, Venture "Extended Edition", null, 4900.00]
[1996, Jeep, Grand Cherokee, MUST SELL!
air, moon roof, loaded, 4799.00]
[1999, Chevy, Venture "Extended Edition, Very Large", null, 5000.00]
[null, null, Venture "Extended Edition", null, 4900.00]

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).