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