定长文件格式

时间:2019-06-13 07:56:45

标签: bean-io

我正在从定长文件中读取数据。

这是文件内容:
Joe Smith Developer 075000 10012009

这是映射文件:

    <beanio>

      <stream name="employeeFile" format="fixedlength">
        <record name="employee" class="Employee" minOccurs="0" maxOccurs="unbounded">
          <field name="firstName" length="10" />
          <field name="lastName" length="10" />
          <field name="title" length="10" />
          <field name="salary"  length="6" />
          <field name="hireDate" format="MMddyy"  minOccurs="0" length="unbounded" maxLength="8"/>
        </record> 
      </stream>

    </beanio>

输出:

    First Name:Joe
    Last Name:Smith    
    Title:Developer 
    Salary:75000
    Hire Date:Thu Oct 01 00:00:00 IST 2009

代码正在读取文件并成功转换为pojo。现在客户需要在我努力实施的奇怪要求。

从文件内容"Joe Smith Developer 075000 10012009"开始,如果最后一个值没有出现或部分不出现,则代码应成功读取内容。

例如:如果文件包含类似"Joe Smith Developer 0750"的内容。这里的薪水长度为4,但我们在映射文件中声明为6,并且没有雇用日期数据。尽管如此,代码仍应成功读取它,就像薪水为0750,雇用日期为null。

我怎么读?

1 个答案:

答案 0 :(得分:0)

我能得到的最好的办法是让它为丢失的字段分配null值。一旦出现字段的任何部分,该字段的整个长度就必须出现在数据中。这是固定长度格式的本质。

使用此映射文件:

<beanio>
  <stream name="employeeFile" format="fixedlength">
    <record name="employee" class="Employee" minOccurs="0" maxOccurs="unbounded">
      <field name="firstName" length="10"/>
      <field name="lastName" length="10"/>
      <field name="title" length="10"/>
      <field name="salary" length="6" minOccurs="0"/>
      <field name="hireDate" format="MMddyyyy" length="8" minOccurs="0"/>
    </record>
  </stream>
</beanio>

您将能够读取以下数据:

Joe1      Smith     Developer 07500010012009
Joe3      Smith     Developer 

输出:

Employee(firstName=Joe1, lastName=Smith, title=Developer, salary=075000, hireDate=Thu Oct 01 00:00:00 SAST 2009)
Employee(firstName=Joe3, lastName=Smith, title=Developer, salary=null, hireDate=null)

但是此行不起作用(如您所知,因此也是这个问题的原因)

Joe2      Smith     Developer 0750

您要么必须告诉提供数据的人员/公司符合数据规范,要么必须先操纵数据,然后才能使用BeanIO读取数据。否则,必须以可变长度格式(例如CSV,管道分隔符或XML)提供数据,然后可以使用BeanIO正确解析

相关问题