导包
pom依赖
<dependencies>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>3.3</version>
</dependency>
</dependencies>
jar包
下载地址:
http://repo.boundlessgeo.com/main/net/sourceforge/javacsv/javacsv/2.1/javacsv-2.1.jar
CSVReader
构造函数
我这里就用参数最多的构造函数吧
CSVReader(Reader reader, int line, CSVParser csvParser, boolean keepCR, boolean verifyReader) {
this.hasNext = true;
this.br = reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader(reader);
this.lineReader = new LineReader(this.br, keepCR);
this.skipLines = line;
this.parser = csvParser;
this.keepCR = keepCR;
this.verifyReader = verifyReader;
}
其中Reader 为传入一个输入流,第二个参数是读取器格式,后几个不懂。一般来说参数只传Reader就够了,其他默认的参数和平时实验生成的CSV数据是一致的。
常用API
读取全部数据,每次把csv里面的一行读成String[],逐行读取写入List
public List<String[]> readAll() throws IOException {
ArrayList allElements = new ArrayList();
while(this.hasNext) {
String[] nextLineAsTokens = this.readNext();
if (nextLineAsTokens != null) {
allElements.add(nextLineAsTokens);
}
}
return allElements;
}
这个就是读下一行
public String[] readNext() throws IOException {
String[] result = null;
do {
String nextLine = this.getNextLine();
if (!this.hasNext) {
return result;
}
String[] r = this.parser.parseLineMulti(nextLine);
if (r.length > 0) {
if (result == null) {
result = r;
} else {
result = this.combineResultsFromMultipleReads(result, r);
}
}
} while(this.parser.isPending());
return result;
}
还有一些就是iterator、close方法,关闭流、迭代器,不做赘述。
CSVWriter
构造函数
我这里就用参数最多的构造函数吧
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
this.resultService = new ResultSetHelperService();
this.rawWriter = writer;
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
其中Writer 为传入一个输出流,后面参数依次是分隔符、前引用符、后引用符、终止符,一般来说参数只传Writer 就够了,其他默认的参数和平时实验生成的CSV数据是一致的。
常用API
写入全部数据,该方法会覆盖整个文件的数据,慎用。每次把List里面的String[]当成CSV里面的一行数据,逐行写入
public void writeAll(List<String[]> allLines) {
Iterator i$ = allLines.iterator();
while(i$.hasNext()) {
String[] line = (String[])i$.next();
this.writeNext(line);
}
}
这个就是写一行,也就是添加在文件末尾
public void writeNext(String[] nextLine) {
this.writeNext(nextLine, true);
}
还有一些就是flush、close方法,关闭流、刷新流,不做赘述。
评论区