Csvbeans: parse CSV in Java

Source: Internet
Author: User

1. Introduction to CSV and csvbeans
CSV: comma seperated values; Description: A row represents a record, and a record has multiple fields (attributes). Each attribute is separated by commas (or other symbols.

Csvbeans open-source project: an open-source tool that converts each line of CSV data into a JavaBean;

Download URL: http://sourceforge.net/projects/csvbeans/files/

Of course, parsing CSV is not only a tool, but also opencsv of Apache;


Dependency packages should also be added in the lib directory, including: commons-resources.jarcommons-logging.jarcommons-lang-2.1.jarcommons-digester-1.7.jarcommons-codec-1.3.jarcommons-beanutils-core.jarcommons-beanutils-bean-collections.jarcommons-beanutils.jar
2. Solving project defects
First, I have found two small problems in this project: (1) CSV file data cannot be separated by \ t; (2) starttag must be included when writing CSV files;

Starttag must exist, which means:Persons----> This is starttagaaa, 20aaa, 20aaa, 20.
The starttag cannot be absent, which means AAA, 20aaa, 20aaa, 20
If starttag is set to null, a problem occurs;

Solution:
(1) For the first problem, if a CSV file is separated by \ t, I wrote a helper class that can be used to rewrite the CSV file to a CSV file separated by commas;

Package com.xiazdong.csv; import Java. io. bufferedreader; import Java. io. file; import Java. io. fileinputstream; import Java. io. inputstreamreader; import Java. io. printwriter; import Java. util. UUID; public class csvutils {/*** this function is used to assist csvbeans. Because this open-source package has a defect, it cannot parse CSV files separated by tab, therefore, this function is used to convert a tab to a comma and overwrite the file to be converted from the original file * @ Param fromfile * @ throws exception */public static void parsefromtabtocomma (File fromfile) throws exc Eption {bufferedreader reader = new bufferedreader (New inputstreamreader (New fileinputstream (fromfile); file tmpfile = new file (UUID. randomuuid (). tostring (); // generate a temporary file, but no printwriter writer = new printwriter (tmpfile); string line = NULL; while (line = reader. readline ())! = NULL) {string ss [] = line. split ("\ t"); // separated by tab (INT I = 0; I <ss. length; I ++) {writer. write (ss [I]); if (I <(ss. length-1) {writer. write (",") ;}} writer. write ("\ n");} writer. close (); reader. close (); If (fromfile. exists () {fromfile. delete (); tmpfile. renameto (fromfile) ;}} public static void main (string [] ARGs) throws exception {parsefromtabtocomma (new file ("src/persons.csv "));}}

(2) For the second problem, you must modify the source code;
Source code download: http://sourceforge.net/projects/csvbeans/files/csvbeans/csvbeans-0.7.1/
Csvbeans-0.7.1 \ SRC \ Java \ org \ csvbeans \ builders \ csvbuilder. Java AddbeansFunction changed to: Public void addbeans (string tag, list beans ){
If (beans! = NULL) {This. Beans. Add (new records (TAG, beans ));}}
WritebeansThe function starts with try {If (tag! = NULL) writer. writeline (TAG); recordspecification record = getrecordspecification (TAG );
After modifying the source code, ant package also needs to be compiled. The ant package automatically generates csvbeans. jar;

Iii. Preparations

1. Write Javabean to indicate a CSV record;
2. write an XML file with the following content: (1) attributes of a CSV record, including the name and maxlen of each attribute; (2) separators between each attribute; (3) classes of JavaBean; (4) parser class and builder class used;

4. Programming

Directory structure:


First, it indicates that both the an and mapping. XML for reading and writing CSV are the same;
1. Read CSV

Person. Java
Mapping. xml
<? XML version = "1.0"?> <Csvbeans> <strategy> <parser classname = "org.csv beans. parsers. csvparser "/> <builder classname =" org.csv beans. builders. csvbuilder "/> </strategy> <property name =" separator "value =", "/> <! -- Delimiter --> <property name = "nostarttag" value = "true"/> <! -- No starttag --> <record classname = "com.xiazdong.csv. domain. Person"> <! -- One record --> <field name = "name" maxlen = "100" required = "true"/> <field name = "Age" maxlen = "10" required = "true "/> </record> </csvbeans>

Read the CSV program:

Private Static void read () throws exception, specificationsfileexception, filenotfoundexception, parsingexception {file F = new file ("src/persons.csv"); csvutils. parsefromtabtocomma (f); // If CSV files are separated by tabs, use this function specificationsfileparser specsparser = new specificationsfileparser (); specificationsfile specs = specsparser. parse (New fileinputstream ("src/mapping. XML "); parsingstrategy parser = specs. getparsingstrategy (); // obtain mapping. csvparserparser in XML. parse (New inputstreamlinesreader (New fileinputstream (F); list products = parser. getbeans (null); // No header for (iterator it = products. iterator (); it. hasnext ();) {person Product = (person) it. next (); system. out. println (product );}}
2. Write CSV

Private Static void write () throws specificationsfileexception, filenotfoundexception, generationexception {list <person> Persons = new arraylist <person> (); persons. add (new person ("I", 20, 20); persons. add (new person ("AAA", 20, 20); persons. add (new person ("AAA", 20, 20); specificationsfileparser specsparser = new specificationsfileparser (); specificationsfile specs = specsparser. parse (New fileinputstream ("src/mapping. XML "); buildingstrategy builder = specs. getbuildingstrategy (); // obtain mapping. in XML, csvbuildercsvbuilder csvbuilder = (csvbuilder) builder; csvbuilder. addbeans (null, persons); csvbuilder. build (New outputstreamlineswriter (New fileoutputstream ("src/output.csv ")));}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.