OpenCSV is a simple java class library for parsing CSV files. It encapsulates the output and reading of CSV format files and can automatically handle special characters in the CSV format. The most important thing is that OpenCSV can be used for commercial- friendly). Specific usage:
Read CSV files
1. Use the Iterator method to read the copied code. The code is as follows:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
2. Use List
Copy the code code as follows:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
Write CSV file
1. Similar to FileReader
Copy the 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. Customize the separator. For example, use tab as the separator. Copy the code as follows:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '/t');
2. You can also use escape characters to copy the code as follows:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '/t', '/'');
3. Start parsing the copied code from the second (n) line. The code is 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 the code code as follows:
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(YourOrderBean.class);
String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean
strat.setColumnMapping(columns);
CsvToBean csv = new CsvToBean();
List list = csv.parse(strat, yourReader);
over