1、pom.xml添加opencsv-3.3.jar依赖:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>3.3</version>
</dependency>
2、读取csv文件:
public void readCsv(String path) {
try {
DataInputStream in = new DataInputStream(new FileInputStream(new File(path)));
// CSVReader csvReader = new CSVReader(new InputStreamReader(in,"GBK"));
CSVReader csvReader = new CSVReader(new InputStreamReader(in, "GBK"), CSVParser.DEFAULT_SEPARATOR,
CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, 1);
String[] strs;
while ((strs = csvReader.readNext()) != null) {
System.out.println(Arrays.deepToString(strs));
}
csvReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3、写入csv文件:
public static void writeFile(String path, String[] strArr, List<String[]> list) {
File csv = new File(path);
if (!csv.exists()) {
try {
csv.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
CSVWriter writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream(csv), "GBK"),
CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER);
writer.writeNext(strArr);
writer.writeAll(list);
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
4、通过maven->download sources可查看jar包的源