使用opencsv(opencsv-2.3.jar),下载地址:http://sourceforge.net/projects/opencsv/files/latest/download
一,读取CSV格式文件:
import java.io.File;
import java.io.FileReader;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
public class ReadCSV {
public static void main(String[] args) throws Exception {
File file = new File("e:\\read.csv");
FileReader fReader = new FileReader(file);
CSVReader csvReader = new CSVReader(fReader);
String[] strs = csvReader.readNext();
if(strs != null && strs.length > 0){
for(String str : strs)
if(null != str && !str.equals(""))
System.out.print(str + " , ");
System.out.println("\n---------------");
}
List<String[]> list = csvReader.readAll();
for(String[] ss : list){
for(String s : ss)
if(null != s && !s.equals(""))
System.out.print(s + " , ");
System.out.println();
}
csvReader.close();
}
}
执行结果如下:
编号 , 姓名 , 备注 ,
---------------
1 , Li , 123456 ,
2 , Sean ,
CSVReader.close()方法本质上是关闭传入其中的FileReader:
private BufferedReader br;
public CSVReader(Reader reader, char separator, char quotechar,
char escape, int line, boolean strictQuotes, boolean ignoreLeadingWhiteSpace) {
this.br = new BufferedReader(reader);
this.parser = new CSVParser(separator, quotechar, escape,
strictQuotes, ignoreLeadingWhiteSpace);
this.skipLines = line;
}
public void close() throws IOException{
br.close();
}
当然分隔符可以不是默认的逗号,只需在创建CSVReader时指定其分隔符即可:
CSVReader csvReader = new CSVReader(fReader, ';');
二,写CSV格式文件:
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import au.com.bytecode.opencsv.CSVWriter;
public class WriteCSV {
public static void main(String[] args) throws Exception {
File file = new File("e:\\write.csv");
Writer writer = new FileWriter(file);
CSVWriter csvWriter = new CSVWriter(writer, ',');
String[] strs = {"abc" , "abc" , "abc"};
csvWriter.writeNext(strs);
csvWriter.close();
}
}
执行结果如下:
CSVWrite的构造方法如下:
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public CSVWriter(Writer writer, char separator) {
this(writer, separator, DEFAULT_QUOTE_CHARACTER);
}
双引号被用作默认的引用符(具体什么意思不清楚)
修改一下CSVReader的初始化方式:
CSVWriter csvWriter = new CSVWriter(writer, ',' , '\\');
CSVReader中使用的是CSVParser中的静态变量:
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
但是在CSVWriter中:
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final char DEFAULT_ESCAPE_CHARACTER = '"';
看来应该是作者的疏忽