如何将分隔符分隔的平面文件解析为POJO对象

5
感谢您能够指点并推荐如何将一个扁平的以管道符分隔的文件解析为JAVA Pojo。 例如: 扁平文件 0001|XYZ|120
需要将其读入到一个具有以下属性的POJO中:
public class pojo {

private String acct;
private String customer;
private int balance;
}

我可以将整个输入文件作为集合读取,但最终需要将每个标记设置为pojo成员。相反,我希望解析为pojo成员。类似于CASTOR XML映射到POJO的内容。

非常感谢您的帮助。提前致谢。


您正在寻找FFPOJO: https://github.com/ffpojo/ffpojo - gibaholms
5个回答

8
你可以使用Bean IO。我已经广泛使用了它。
将你的XML配置为以下结构:
<stream name="employees" format="delimited" strict="true">
  <parser>  
    <property name="delimiter" value="|" />
  </parser>
  <record name="test" class="example.Pojo" minOccurs="1" maxOccurs="1">
      <field name="act" />
      <field name="customer" />
      <field name="balance" type="int" />
    </record>
 </stream>

更多详细信息,请参阅此处


3

2

我会逐行阅读,分割数值并调用POJO构造函数(如果没有,请创建一个),例如:

   List<pojo> pojoList = new ArrayList<pojo>();
   BufferedReader br = new BufferedReader(new FileReader("FlatFile.txt"));
   String line = "";
   while((line = br.readLine()) != null) {  
       String[] fields = line.split("\|");
       pojo p = new pojo(fields[0], fields[1], fields[2]);
       pojoList.add(p);
   }

谢谢Yogendra,我刚好发现了OPENCSV,它有很好的功能来完成这个任务。 - Anand
1
我认为正则表达式应该是: String fields[] = line.split("\|"); - Natasha Kurian

0
感谢大家的快速回复。根据Thihara的建议,我成功地让OPENCSV工作了(感谢Glen Smith和Kyle Miller在Bean Mapping方面的贡献)。从OPENCSV获取opencsv-2.3.jar。
我会发布完整的源代码以使像我这样的其他人受益。
输入文件
/**
     * Input File: acct_os.txt
     * 
     * <pre>
     * 12345|ABC Company|120.45
     * 34567|XYZ Company|45.00
     * 99999|MNC Bank|67.00
     */

/**
 * Bind File to a POJO
 * 
 * @param inputFile
 * @param delim
 * @throws FileNotFoundException
 */
public void bindFileToPojo(String inputFile, char delim) throws FileNotFoundException {

    System.out.println("\n===== Reading to a POJO\n");

    ColumnPositionMappingStrategy<TestCustomerBean> strat = new ColumnPositionMappingStrategy<TestCustomerBean>();
    strat.setType(TestCustomerBean.class);
    /**
     * the fields to bind do in your JavaBean
     */
    String[] columns = new String[] { "acct", "customer", "balance" };
    strat.setColumnMapping(columns);

    CsvToBean<TestCustomerBean> csv = new CsvToBean<TestCustomerBean>();
    /**
     * Read file contents to list using CSVReader
     */
    List<TestCustomerBean> list = csv.parse(strat, new CSVReader(new FileReader(inputFile), delim));
    /**
     * Display column mapping
     */
    displayColumnMapping(strat.getColumnMapping());

    for (TestCustomerBean bean : list) {
        System.out.println("account: ["
                + bean.getAcct()
                    + "] customer: ["
                    + bean.getCustomer()
                    + "] balance: ["
                    + bean.getBalance()
                    + "]");
    }
}

/**
 * Display column mapping
 * 
 * @param columns
 */
private void displayColumnMapping(String[] columns) {
    for (String column : columns) {
        System.out.println("Column Mapping-->" + column);
    }
}

TestCustomerBean(省略getter/setter)

private String acct;
private String customer;
private Double balance;

输出将会是

===== 读取到POJO

列映射-->账户
列映射-->客户
列映射-->余额
账户:[12345] 客户:[ABC公司] 余额:[120.45]
账户:[34567] 客户:[XYZ公司] 余额:[45.0]
账户:[99999] 客户:[MNC银行] 余额:[67.0]


0

另一个论坛推荐了smooth,根据JayaMohan(谢谢)的建议,我能够使用beanio将Flat文件映射到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"?>
<beanio xmlns="http://www.beanio.org/2012/03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.beanio.org/2012/03 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>

</beanio>

输出将会是:

acct: [12345] customer: [ABC Company] balance: [120.45]
acct: [34567] customer: [XYZ Company] balance: [45.0]
acct: [99999] customer: [MNC Bank] balance: [67.0]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接