用Java解析平面文件 [英] Parsing a flat file in Java

查看:116
本文介绍了用Java解析平面文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个平面文件,其中数据以基于位置的格式存储。例如。从 1到5 - 存储一些 x 值,从 6到13 - 存储一些 y 值,从 14到18 - 存储了一些 z 值等等。
我需要解析文件并获取这些值并填充bean。

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.

任何人都可以告诉我,我可以解决它的最佳方式意味着我可以解析文件。我使用的是Java 6.

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中非复杂,固定长度的行应该很容易。

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



<如果你真的很认真地将几个大的平面文件映射到java,你可能想要使用一些库。

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

Smooks 让你在XML文件中指定映射,并将smooks运行时映射从字段到对象。还有一个用于图形映射的Eclipse IDE。这个库是有点重量级。

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.

我真的很喜欢 Bindy Apache Camel 中的a>组件。它需要引入消息路由器的开销,但是可以注释普通的java类并且只需一次执行映射和java类。

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;

这篇关于用Java解析平面文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆