在Java中解析固定宽度格式文件的最佳方法是什么?

Mat*_*mes 17 java parsing fixed-width

我有一个来自供应商的文件,每行有115个固定宽度的字段.将该文件解析为115个字段的最佳方法是什么,以便我可以在我的代码中使用它们?

我首先想到的是只是为了让常数为每场像NAME_START_POSITIONNAME_LENGTH使用substring.这看起来很难看,所以我很好奇是否还有其他推荐方法可以做到这一点.谷歌搜索出现的几个图书馆似乎都没有.谢谢

Pas*_*ent 21

我会使用扁平文件解析器,如扁虫,而不是重新发明轮子:它有一个干净的API,使用简单,具有良好的错误处理和简单的文件格式描述符.另一种选择是jFFP,但我更喜欢第一种.


p3t*_*t0r 7

我已经使用fixedformat4j玩了arround它非常好.易于配置转换器等.


Jer*_*kes 5

uniVocity解析器带有FixedWidthParserFixedWidthWriter,可以支持棘手的固定宽度格式,包括具有不同字段的行,填充等。

// creates the sequence of field lengths in the file to be parsed
FixedWidthFields fields = new FixedWidthFields(4, 5, 40, 40, 8);

// creates the default settings for a fixed width parser
FixedWidthParserSettings settings = new FixedWidthParserSettings(fields); // many settings here, check the tutorial.

//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 File("path/to/fixed.txt")));
Run Code Online (Sandbox Code Playgroud)

这是一些解析示例各种固定宽度输入的。

这是一些用于编写常规示例的其他示例,以及其他针对固定宽度格式的固定宽度示例

披露:我是这个库的作者,它是开源的并且免费的(Apache 2.0许可证)