Java 固定宽度文件格式读写库

7
我正在寻找一个好的Java库,可以轻松地读写固定宽度的文件。这是为了维护遗留系统,即需要使用COBOL文件。如果您有任何建议,将不胜感激!谢谢。

这里也有人问过同样的问题:https://dev59.com/9lvUa4cB1Zd3GeqPtnA5 - wrschneider
我最终使用了BeanIO,但还是感谢你的帮助!让我朝着正确的方向前进。 - TyC
5个回答

6
uniVocity-parsers可以解析和写入固定宽度的输入(以及CSV和TSV)。它具有许多您可以使用的功能。
示例输入:
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_

需要阅读的代码:

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));

输出:

[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]

声明:我是这个库的作者。它是开源和免费的(使用Apache V2.0许可证)。


这是一个非常好的解析器,但它不允许你从内部Java结构转换为固定宽度文件,也就是说,它只是一个读取器,而不是一个写入器。 - alianos-
@alianos 看起来你还没有尝试过FixedWidthWriter。在这里可以查看一些示例:https://github.com/uniVocity/univocity-parsers/blob/master/src/test/java/com/univocity/parsers/examples/FixedWidthWriterExamples.java - Jeronimo Backes

4
我会使用ByteBuffer,可能与映射的内存文件一起使用。这样可以读写big或little endian的原始类型。对于固定宽度的二进制数据,此选项最佳。
对于固定宽度的文本,您可以使用BufferedReader.readLine()和String.substring(from, to)获取所需字段。要输出固定宽度字段,您可以使用PrintWriter.printf(format,fields...)。

3

1

基于模式的方法:

  • JSaPar 允许您指定一个模式,以便解析或生成固定宽度文本。还进行一些基本类型检查和类型转换。
  • 这里还列出了其他库(链接),可能对您有所帮助。

1

你可以看一下以下资源:

  • JRecord Java读写Cobol文件的库,支持多种Cobol方言和格式
  • cb2java 读取Cobol文件的工具
  • Legstar 处理Cobol数据的库
  • cb2xml 将Cobol文件转换为Xml格式的工具

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接