JAVA Bean IO读取带有数值空格的CSV文件

时间:2014-09-12 21:27:38

标签: java csv bean-io

我正在尝试读取具有空格的某些整数值的CSV文件。我无法获得具有没有空格的整数值的文件。使用bean io,当我尝试读取此文件时,它会在读取整数值时出现转换错误。这是我的豆子

public class PetOwner {
    private String name;
    private int age;
    private int numberOfPets;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getNumberOfPets() {
        return numberOfPets;
    }
    public void setNumberOfPets(int numberOfPets) {
        this.numberOfPets = numberOfPets;
    }

}

这是我的映射文件

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beanio xmlns="http://www.beanio.org/2012/03">
    <stream name="petowner" format="csv">
    <parser>
        <property name="delimiter" value="," />
        <property name="whitespaceAllowed" value="true" />
    </parser>
        <record name="petowner" class="com.PetOwner ">
            <field name="name" type="String" />     
            <field name="age" type="int" />
            <field name="numberOfPets" type="int"/>
        </record>
    </stream>
</beanio>

这是我正在尝试阅读的文件内容..注意整数值之前的空格。有一些设计限制,我无法更改age和numberOfPets为String的数据类型。

 John,   22,  1
 Ashley,   20,  3

1 个答案:

答案 0 :(得分:0)

您可以在映射的字段声明中使用trim="true"。然后在修剪后验证值。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <beanio xmlns="http://www.beanio.org/2012/03">
<stream name="petowner" format="csv">
    <parser>
        <property name="delimiter" value="," />
        <property name="whitespaceAllowed" value="true" />
    </parser>
    <record name="petowner" class="com.PetOwner ">
        <field name="name" type="String" />     
        <field name="age" type="int" trim="true" />
        <field name="numberOfPets" type="int" trim="true" />
    </record>
</stream>