Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a fixed-width formatted file in Java

I've got a file from a vendor that has 115 fixed-width fields per line. How can I parse 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 about better ways of doing this. None of the couple of libraries a Google search turned up seemed any better, either.

like image 946
MattGrommes Avatar asked Oct 22 '09 20:10

MattGrommes


People also ask

How do you read a fixed width file in Java?

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 File("path/to/fixed.

What is fixed width delimiter?

Data in a fixed-width text file is arranged in rows and columns, with one entry per row. Each column has a fixed width, specified in characters, which determines the maximum amount of data it can contain. No delimiters are used to separate the fields in the file.

What is parse file in Java?

ParseFile is a local representation of a file that is saved to the Parse cloud. The workflow is to construct a ParseFile with data and optionally a filename. Then save it and set it as a field on a ParseObject .


2 Answers

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.

like image 113
Pascal Thivent Avatar answered Oct 07 '22 03:10

Pascal Thivent


I've played arround with fixedformat4j and it is quite nice. Easy to configure converters and the like.

like image 29
p3t0r Avatar answered Oct 07 '22 05:10

p3t0r