简体   繁体   English

用Java解析平面文件

[英]Parsing a flat file in Java

I have a flat file in which data is stored in position based format For eg. 我有一个平面文件,其中数据以基于位置的格式存储,例如。 from 1 to 5 - some x value is stored, from 6 to 13 - some y value is stored, from 14 to 18 - some z value is stored and so on.. I need to parse the file and get those values and populate a bean. 1到5-存储一些x值,从6到13-存储一些y值,从14到18-存储一些z值,依此类推。.我需要解析文件并获取这些值并填充一个豆角,扁豆。

Can anyone please tell me the best way I can go about it means how I can parse the file.I am using Java 6. 谁能告诉我最好的解决方法,这意味着我可以解析文件。我使用的是Java 6。

Non complex, fixed length rows should be very easy in plain java. 在普通的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. 如果您真的很认真地将几个大型平面文件映射到Java,则可能需要使用一些库。

Smooks let's you specify the mapping in a XML file, and have the smooks runtime map from fields to an object. 烟雾使您可以在XML文件中指定映射,并使烟雾运行时映射从字段到对象。 There is also an Eclipse IDE for graphical mapping. 还有一个用于图形映射的Eclipse IDE。 This library is somewhat heavyweight. 这个库有些重量级。

I really like the Bindy component in Apache Camel . 我真的很喜欢Apache Camel中Bindy组件。 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. 这需要引入消息路由器的开销,但是可以注释普通的Java类,并且只需一次完成映射和Java类即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM