Opencsv is a simple Java class library for parsing CSV files that encapsulates the output and reading of CSV format files, automates the processing of special characters in CSV format, and most importantly opencsv can be used for commercialization (commercial-friendly). Specific methods of use:
Read CSV file
1, the use of iterator way to read
Copy Code code as follows:
Csvreader reader = new Csvreader (New FileReader ("Yourfile.csv"));
String [] nextline;
while ((nextline = Reader.readnext ())!= null) {
Nextline[] is a array of values from the line
System.out.println (Nextline[0] + nextline[1] + "etc ...");
}
2. Use list
Copy Code code as follows:
Csvreader reader = new Csvreader (New FileReader ("Yourfile.csv"));
List myentries = Reader.readall ();
Write CSV file
1, similar to FileReader
Copy Code code as follows:
Csvwriter writer = new Csvwriter (New FileWriter ("Yourfile.csv"), ' t ');
Feed in your array (or convert your data to an array)
string[] entries = "First#second#third". Split ("#");
Writer.writenext (entries);
Writer.close ();
Custom Separator
1, custom separator, such as the use of tab separator
Copy Code code as follows:
Csvreader reader = new Csvreader (New FileReader ("Yourfile.csv"), ' t ');
2, also can use the escape character
Copy Code code as follows:
Csvreader reader = new Csvreader (New FileReader ("Yourfile.csv"), ' \ t ', ' \ ');
3, from the second (n) line to start parsing
Copy Code code as follows:
Csvreader reader = new Csvreader (New FileReader ("Yourfile.csv"), ' t ', ' \ ', 2;
Dump SQL Tables
Java.sql.ResultSet Myresultset = .....
Writer.writeall (Myresultset, includeheaders);
Generate JavaBeans
Copy Code code as follows:
Columnpositionmappingstrategy strat = new Columnpositionmappingstrategy ();
Strat.settype (Yourorderbean.class);
string[] columns = new string[] {"Name", "OrderNumber", "id"}; The fields to bind does in your JavaBean
strat.setcolumnmapping (columns);
Csvtobean csv = new Csvtobean ();
List List = Csv.parse (strat, Yourreader);
Finish