package util;
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.List;
/**
*
* CSV读写工具类
* @className CSVUtil
* @author Jeason
* @date 2019年9月7日
*/
public class CSVUtil {
private static char separator = ',';
/**
* 读取CSV文件
* @param filename:全路径名
*/
public static List<String[]> readCSV(String filename) throws Exception {
System.out.println("==================开始读取文件"+filename+"==================");
CsvReader reader = null;
List<String[]> dataList = new ArrayList<String[]>();
try {
//如果生产文件乱码,windows下用gbk,linux用UTF-8
reader = new CsvReader(filename, separator, Charset.forName("UTF-8"));
// 读取表头
reader.readHeaders();
String[] headArray = reader.getHeaders();//获取标题
System.out.println("标题:" );
for (String string : headArray) {
System.out.print(string + ",");
}
System.out.println();
// 逐条读取记录,直至读完
System.out.println("内容:" );
while (reader.readRecord()) {
String[] str = reader.getValues();
if (str != null && str.length > 0) {
dataList.add(str);
for (String s : str) {
System.out.print(s + ",");
}
System.out.println();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != reader) {
reader.close();
}
}
System.out.println("==================读取文件结束==================");
return dataList;
}
/**
* 生成CSV文件
* @param dataList:数据集
* @param filename:全路径名
*/
public static boolean createCSV(List<String[]> dataList, String filename) throws Exception {
boolean isSuccess = false;
CsvWriter writer = null;
FileOutputStream out = null;
try {
out = new FileOutputStream(filename, 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;
}
}