BeanIO fixed length file writer Scala- Avoid one field from writing

201 views Asked by At

I am trying to write a csv file from scala case class using fixed length file BeanIO library.

sample code

case class employee(id:String,name:String,dob:String)

<record name="emp" class="employee">
 <field name="id" position="0" length="5" getter="#1" setter="id"/> 
 <field name="name" position="5" length="5" getter="#2" setter="name"/>
 <field name="dob" position="10" length="5" getter="#3" setter="dob"/> 
</record>

But I want to avoid dob from writing in the csv file. If I removed that line from xml, it will throw error

Could anyone suggest any way to do that other than removing it from case class or make field length as "zero".

1

There are 1 answers

0
nicoschl On

How about treating the dob field as a constant?

If a bean property does not map to a field in the stream, a constant property value can still be set using a property element. Like a field, all properties must specify a name attribute, which by default, is used to get and set the property value from the bean object. Properties also require a value attribute for setting the textual representation of the property value. The value text is type converted using the same rules and attributes (type, typeHandler and format) used for field type conversion described above. Collection type properties are not supported.

Try this:

<record name="emp" class="employee">
 <field name="id" position="0" length="5" getter="#1" setter="id"/> 
 <field name="name" position="5" length="5" getter="#2" setter="name"/>
 <property name="dob" position="10" length="5" getter="#3" setter="dob" value="" /> 
</record>

The value for dob would then not be dependent on the actual value it is set to or not in your class. This way you control the output. You can also experiment with changing the name of the property to something that is not present in the class.