参考 : Java实现CSV文件的读写_thebigdipperbdx的博客-优快云博客
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class CSVUtil {
public static char separator = ',';
public static void main(String[] args) {
// 测试导出
String filePath = "/Users/leyili/Desktop/test/scoreInfo.csv";
List<String[]> dataList = new ArrayList<String[]>();
//添加标题
dataList.add(new String[]{"学号", "姓名", "分数"});
for (int i = 0; i < 10; i++) {
dataList.add(new String[]{"2010000" + i, "张三" + i, "8" + i});
}
createCSV(dataList, filePath);
// 读取CSV文件
List<String[]> lists = readCSV(filePath, true);
lists.forEach(list -> {
for (String s : list) {
System.err.print(s + " ");
}
System.err.println();
});
}
/**
* 读取CSV文件
*
* @param filePath:全路径名
*/
public static List<String[]> readCSV(String filePath, Boolean isReadHeader){
CsvReader reader = null;
List<String[]> dataList = new LinkedList<>();
try {
//如果生产文件乱码,windows下用gbk,linux用UTF-8
reader = new CsvReader(filePath, separator, Charset.forName("UTF-8"));
// 读取表头
reader.readHeaders();
if (isReadHeader != null && isReadHeader) {
//获取标题
String[] headArray = reader.getHeaders();
dataList.add(headArray);
}
// 逐条读取记录,直至读完
while (reader.readRecord()) {
String[] lines = new String[reader.getColumnCount()];
for (int i = 0; i < reader.getColumnCount(); i++) {
lines[i] = reader.get(i);
}
dataList.add(lines);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != reader) {
reader.close();
}
}
return dataList;
}
/**
* 生成CSV文件
*
* @param dataList:数据集
* @param filePath:全路径名
*/
public static boolean createCSV(List<String[]> dataList, String filePath){
boolean isSuccess = false;
CsvWriter writer = null;
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath, true);
//如果生产文件乱码,windows下用gbk,linux用UTF-8
writer = new CsvWriter(out, separator, Charset.forName("UTF-8"));
for (String[] strs : dataList) {
writer.writeRecord(strs);
}
isSuccess = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != writer) {
writer.close();
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSuccess;
}
}
本文介绍使用Java进行CSV文件的读取与写入操作的方法,包括依赖库的引入、代码实现及运行示例。通过具体实例展示了如何创建CSV文件、添加数据及读取CSV文件内容。
1705





