Parsing a flat file in Java

笑着哭i 提交于 2019-12-04 11:52:50

Non complex, fixed length rows should be very easy in plain java.

Why don't you just use plain basic substring? I've seen this used in parsing quite big flat files, and it's not as bad as it sounds. Pretty easy to get an overview from it as well.

myObject.setX(Integer.parseInt(input.substring(0,4)));
myObject.setY(input.substring(5,12); 
..  

If you are really serious in mapping several large flat files to java, you might want to use some library.

Smooks let's you specify the mapping in a XML file, and have the smooks runtime map from fields to an object. There is also an Eclipse IDE for graphical mapping. This library is somewhat heavyweight.

I really like the Bindy component in Apache Camel. It requires the overhead of introducing a message router, but it's possible to annotate plain java classes and just do the mapping and the java class in one go.

// Like this
@FixedLengthRecord(length=54, paddingChar=' ')
public static class Order {

    @DataField(pos = 1, length=2)
    private int orderNr;

    @DataField(pos = 3, length=2)
    private String clientNr;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!