first, CSV and Csvbeans introduction
Csv:comma seperated Values; Description: A row represents a record, and a record has multiple fields (attributes), each separated by commas (or other symbols). Csvbeans Open Source project: Convert each line of data in CSV into JavaBean open source tools; Download url:http://sourceforge.net/projects/csvbeans/files/
Of course, parsing CSV is not only a tool, there are Apache opencsv, etc.;
The dependency package is also added to the Lib directory, including: Commons-resources.jar Commons-logging.jar Commons-lang-2.1.jar Commons-digester-1.7.jar Commons-codec-1.3.jar Commons-beanutils-core.jar Commons-beanutils-bean-collections.jar Commons-beanutils.jar
Ii. Project Defect Resolution
First of all, this project I currently identified two small problems: (1) CSV file data can not be separated by \ T, (2) write a CSV file, must have starttag;
Must have Starttag means: Persons ----> This is starttag aaa,20 aaa,20 aaa,20 Can not without starttag means: aaa,20 aaa,20 aaa,20 If the starttag is set to NULL, there will be a problem; |
Solve:
(1) For the first question, if a CSV file exists with \ t, then I write a helper class that can be used to rewrite this CSV file into a comma-separated CSV file;
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 flaw in that it cannot parse the tab-delimited CSV, so this function is specifically used to convert tab to commas and overwrite the original file * @param from File required to convert * @throws Exception/public static void Parsefromtabtocomma (file fromfile) throws exception{buffered
Reader reader = new BufferedReader (new InputStreamReader (New FileInputStream (FromFile)); File Tmpfile = new file (Uuid.randomuuid (). toString ());
Generates temporary files, but does not eventually exist printwriter writer = new PrintWriter (tmpfile);
String line = null;
while ((Line=reader.readline ())!=null) {String ss[] = Line.split ("\\t");//tab-delimited for (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 question, it is necessary to modify the source code;
SOURCE Download: HTTP://SOURCEFORGE.NET/PROJECTS/CSVBEANS/FILES/CSVBEANS/CSVBEANS-0.7.1/
Csvbeans-0.7.1\src\java\org\csvbeans\builders\csvbuilder.java
AddbeansThe function is changed to: public void Addbeans (String tag, List beans) {if (beans!= null) {This.beans.add (new Records (t AG, beans)); } }
Writebeansfunction to start with: try {if (tag!=null) writer.writeline (tag); Recordspecification record = getrecordspecification (tag);
After the revision of the source code also need to use ant compilation, ant package automatically generated Csvbeans.jar;
Iii. Preliminary Preparation
1. Write JavaBean to represent a CSV record;
2. Write an XML file that reads: (1) The attributes of a CSV record, the name of each attribute, the MaxLen, (2) The separator between each attribute, (3) The Class of JavaBean, (4) The parser class, the builder class;
Iv. Preparation of procedures
Directory structure:
First, the JavaBean and mapping.xml that read CSV and write to CSV are the same;
1. Read CSV
Person.java slightly
Mapping.xml
<?xml version= "1.0"?>
<csvbeans>
<strategy>
<parser classname= " Org.csvbeans.parsers.CSVParser "/>
<builder classname= org.csvbeans.builders.CSVBuilder"/>
< /strategy>
<property name= "separator value=", "/> <!--separator--> <property" Name= "
Value= "true"/> <!--no starttag-->
<record classname= "Com.xiazdong.csv.domain.Person" > < !--a record-->
<field name= "name" maxlen= "M" required= "true"/> <field "Age
" Name= "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 the CSV file is tab-delimited, you need to use this function
specificationsfileparser specsparser = new Specificationsfileparser ();
Specificationsfile specs = specsparser.parse (new FileInputStream ("Src/mapping.xml"));
Parsingstrategy parser = Specs.getparsingstrategy (); Obtain the Csvparser parser.parse (new Inputstreamlinesreader (new FileInputStream (f)) in Mapping.xml
;
List products = Parser.getbeans (null); No head 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");
Persons.add (New person ("AAA",);
Persons.add (New person ("AAA",);
Specificationsfileparser specsparser = new Specificationsfileparser ();
Specificationsfile specs = specsparser.parse (new FileInputStream ("Src/mapping.xml"));
Buildingstrategy builder = Specs.getbuildingstrategy (); Obtain the Csvbuilder
csvbuilder csvbuilder = (csvbuilder) builder in Mapping.xml;
Csvbuilder.addbeans (null, persons);
Csvbuilder.build (New Outputstreamlineswriter FileOutputStream ("Src/output.csv"));
}