java 如何将分隔的平面文件解析为 POJO

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13853357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:11:37  来源:igfitidea点击:

How to Parse a delimited flat file to a POJO

java

提问by Anand

Appreciate if someone could point and recommend on how to parse a flat pipe delimited file to JAVA Pojo.

感谢有人可以指出并推荐如何将扁平管道分隔的文件解析为 JAVA Pojo。

eg. Flat File 0001|XYZ|120

例如。平面文件 0001|XYZ|120

this is required to be read into a POJO having

这需要被读入具有

public class pojo {

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

I can read entire input file as a collection, however, would end up setting each token into a pojo member. Instead, I would like to parse into pojo members. Something similar to CASTOR XML mapping to POJO.

我可以将整个输入文件作为一个集合读取,但是,最终会将每个令牌设置为一个 pojo 成员。相反,我想解析成 pojo 成员。类似于 CASTOR XML 映射到 POJO 的东西。

Appreciate any help in this regards. Thanks in advance

感谢这方面的任何帮助。提前致谢

回答by Jayamohan

You can use Bean IO. I have been using this extensively.

您可以使用Bean IO。我一直在广泛使用它。

Configure your XML as something like this

像这样配置你的 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>

Refer herefor more details.

请参阅此处了解更多详情。

回答by Thihara

OopenCSV http://opencsv.sourceforge.net/has what you are looking for. Just change the delimiter to |from ,. And you should be all set.

OopenCSV http://opencsv.sourceforge.net/有你要找的东西。只需将分隔符更改为|from ,。你应该准备好了。

回答by Yogendra Singh

I would simply read one line at a time, split the values and call the POJO constructor(if not available, create one) e.g.:

我只会一次读取一行,拆分值并调用 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);
   }

回答by Anand

Thanks all for quick responses. Based on Thihara's recommendations, managed to get OPENCSV working ( Thanks to Glen Smith and Kyle Miller for their contributions on Bean Mapping) Get opencsv-2.3.jar from OPENCSV

感谢大家的快速回复。根据 Thihara 的建议,设法让 OPENCSV 工作(感谢 Glen Smith 和 Kyle Miller 对 Bean Mapping 的贡献)从OPENCSV获取 opencsv- 2.3.jar

I am posting full source to benefit others like me.

我正在发布完整的源代码,以使像我这样的人受益。

Input File

输入文件

/**
     * 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 omitted)

TestCustomerBean(省略getter/setter)

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

Output would be

输出将是

===== Reading to a POJO

===== 读取 POJO

Column Mapping-->acct
Column Mapping-->customer
Column Mapping-->balance
account: [12345] customer: [ABC Company] balance: [120.45]
account: [34567] customer: [XYZ Company] balance: [45.0]
account: [99999] customer: [MNC Bank] balance: [67.0]

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

回答by Anand

Yet another forum recommended smooooth as per suggestions from JayaMohan (Thanks), I am able to get Flat file mapped to a POJO using beanio. You can get beanio

另一个论坛根据 JayaMohan 的建议推荐了 smooooth(谢谢),我能够使用 beanio 将平面文件映射到 POJO。你可以得到beanio

Full source of using 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();
}

Mapping File

映射文件

<?xml version="1.0" encoding="UTF-8"?>

http://www.beanio.org/2012/03/mapping.xsd">

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>

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

输出将是
账户:[12345] 客户:[ABC 公司] 余额:[120.45] 账户
:[34567] 客户:[XYZ 公司] 余额:[45.0]
账户:[99999] 客户:[MNC 银行] 余额:[67.0] ]