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);
完