另一个论坛根据 JayaMohan 的建议推荐了 smooooth(谢谢),我可以使用 beanio 将平面文件映射到 POJO。你可以得到beanio
使用beanio的完整源码
/**
* Read inputFile and map to BeanIO Mapping file and bind to pojo
*
* @param inputFile
* @param mappingFile
*/
public void flatToBeanReader(String inputFile, String mappingFile) {
/**
* create a StreamFactory
*/
StreamFactory factory = StreamFactory.newInstance();
/**
* load the mapping file
*/
factory.load(mappingFile);
/**
* use a StreamFactory to create a BeanReader
*/
BeanReader in = factory.createReader("customers", new File(inputFile));
TestCustomerBean cust;
while ((cust = (TestCustomerBean) in.read()) != null) {
System.out.println("acct: ["
+ cust.getAcct()
+ "] customer: ["
+ cust.getCustomer()
+ "] balance: ["
+ cust.getBalance()
+ "]");
}
in.close();
}
映射文件
<?xml version="1.0" encoding="UTF-8"?>
http://www.beanio.org/2012/03/mapping.xsd">
<stream name="customers" format="delimited" strict="false">
<parser>
<property name="delimiter" value="|" />
</parser>
<record name="cust" class="TestCustomerBean">
<field name="acct" />
<field name="customer" />
<field name="balance" type="Double" />
</record>
</stream>
输出将是
账户:[12345] 客户:[ABC 公司] 余额:[120.45] 账户
:[34567] 客户:[XYZ 公司] 余额:[45.0]
账户:[99999] 客户:[MNC 银行] 余额:[67.0 ]