我正在寻找一个好的Java库,可以轻松地读取/写入固定宽度的文件。需要维护遗留系统,即使用COBOL需要文件。
非常感谢任何建议!
感谢。
答案 0 :(得分:4)
您还可以查看Fixedformat4j:http://fixedformat4j.ancientprogramming.com/
这是该库的确切目的
答案 1 :(得分:4)
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许可证)。
答案 2 :(得分:2)
我会使用ByteBuffer,可能还有内存映射文件。这允许在大端或小端中读/写原始类型。此选项最适用于固定宽度的二进制数据。
对于固定宽度的文字,您可以使用BufferedReader.readLine()
和String.substring(from, to)
来获取所需的字段。要输出固定宽度字段,您可以使用PrintWriter.printf(format, fields ...)
。
答案 3 :(得分:1)
你可以看看
答案 4 :(得分:1)
基于模式的方法: