简体   繁体   中英

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

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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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