OpenCSV是一個簡單的用於解析CSV檔案的java類庫,它封裝了CSV格式檔案的輸出和讀入,可以自動處理CSV格式中的特殊字元,最重要的是OpenCSV可以用於商業化(commercial-friendly)。具體的使用方法:
讀CSV檔案
1、使用Iterator方式讀
複製代碼 代碼如下:
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、使用List
複製代碼 代碼如下:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
寫CSV檔案
1、類似於FileReader
複製代碼 代碼如下:
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();
自訂分隔字元
1、自訂分隔字元,如使用tab為分隔字元
複製代碼 代碼如下:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t');
2、同樣可以使用轉義符
複製代碼 代碼如下:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t', '\'');
3、從第二(n)行開始解析
複製代碼 代碼如下:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t', '\'', 2);
dump SQL tables
java.sql.ResultSet myResultSet = ....
writer.writeAll(myResultSet, includeHeaders);
產生Javabeans
複製代碼 代碼如下:
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);
完