Java中應用opencsv讀寫csv文件示例。本站提示廣大學習愛好者:(Java中應用opencsv讀寫csv文件示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java中應用opencsv讀寫csv文件示例正文
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);
完