How to skip the first row (header row) in CSV file

2,312 views
Skip to first unread message

storyr...@yahoo.com

unread,
Aug 29, 2014, 3:28:26 AM8/29/14
to bea...@googlegroups.com
Hi

How do I tell the StreamBuilder or BeanIO mapping to skip the first line in the CSV file? I have a csv file which has a header row that provides filed names. There is no row discriminator here.

E.g.

order_no | line_no |  items_no |  qty
100000    | 1          |  ABC        | 20
100000    | 2          |  XYZ        | 10

Please help. Thanks.

Maxime Bochon

unread,
Aug 30, 2014, 8:01:46 AM8/30/14
to bea...@googlegroups.com
Hi,

I suggest the following solution I used personally on a recent project:

 - Describe your stream as made of 1 header record and 0 to N line records:

<stream name="my-company-order" format="delimited">
<parser>
<property name="delimiter" value="|" />
</parser>
<record name="order-header" minOccurs="1" maxOccurs="1" class="my.company.model.Order">
<field name="order" ignore="true" literal="order_no" />
<field name="line"  ignore="true" literal="line_no"  />
<field name="items" ignore="true" literal="items_no" />
<field name="qty"   ignore="true" literal="qty"      />
</record>
<record name="order-line" minOccurs="0" maxOccurs="unbounded" class="my.company.model.Order">
<field name="order" type="int"    />
<field name="line"  type="int"    />
<field name="items" type="string" />
<field name="qty"   type="int"    />
</record>
</stream>

 - You can reuse the same bean used for the line record for the header record as soon as you set the ignore attribute to true for each of its fields.
 - You can still use the literal attribute to ensure that the header has valid column names.

 - Now use the getLineNumber method of your BeanReader to ignore the first line:

BeanReader reader = factory.createReader("my-company-order", inputFile);
for (boolean endOfStream = false; !endOfStream; ) {
Order record = (Order) reader.read();
if (record != null) {
// Ignore first line
if (reader.getLineNumber() > 1) {
// do whatever with the record...
}
} else endOfStream = true;
}
reader.close();

I hope that will help.
Reply all
Reply to author
Forward
0 new messages