http://blog.csdn.net/loongshawn/article/details/53423121
http://javacsv.sourceforge.net/
转载请注明来源-作者@loongshawn:http://blog.csdn.net/loongshawn/article/details/53423121
1 背景
CSV文件的读写其实是有很多方法的,在这里介绍一种利用第三方jar包来读写CSV文件的方法。
日常工作中,如果有现成的第三方工具包,咱最好还是用现成的,有利于提升效率及降低异常率,成熟的三方工具包比较靠谱。
2 JavaCSV API
maven依赖
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.1</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
API 说明文档:http://javacsv.sourceforge.net/
JavaCSV官网:https://sourceforge.net/projects/javacsv/
3 代码实现
3.1 读操作
public static void read(){
String filePath = "XXX.csv";
try {
// 创建CSV读对象
CsvReader csvReader = new CsvReader(filePath);
// 读表头
csvReader.readHeaders();
while (csvReader.readRecord()){
// 读一整行
System.out.println(csvReader.getRawRecord());
// 读这行的某一列
System.out.println(csvReader.get("Link"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
3.2 写操作
public static void write(){
String filePath = "/Users/dddd/test.csv";
try {
// 创建CSV写对象
CsvWriter csvWriter = new CsvWriter(filePath,‘,‘, Charset.forName("GBK"));
//CsvWriter csvWriter = new CsvWriter(filePath);
// 写表头
String[] headers = {"编号","姓名","年龄"};
String[] content = {"12365","张山","34"};
csvWriter.writeRecord(headers);
csvWriter.writeRecord(content);
csvWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 顶
- 8
- 踩
- 2
时间: 2024-10-09 00:44:15